如何将perl哈希数组编码为未命名的JSON数组?

时间:2015-10-28 14:42:57

标签: arrays json perl hash

我有一个哈希数组,我想将其转换为未命名的JSON数组。

如果我有一个哈希数组,那么我会尝试编码为JSON:

my @labs = ();  
push (@labs, {id=>'1', title=>'Lab1'});  
push (@labs, {id=>'2', title=>'Lab2'});  
my $json_text = to_json {\@labs}, {ascii=>1, pretty => 1};  

然后生成的JSON看起来像:

{
   "ARRAY(0x358a18)" : null
}

实际上我希望它看起来像:

[  
   {"title" : "Lab1", "id" : "1"},  
   {"title" : "Lab2", "id" : "2"}  
]  

2 个答案:

答案 0 :(得分:6)

\@labs周围移除花括号 - 他们将您创建的数组转换为匿名哈希值,然后再将其传递给to_json

#!/usr/bin/perl -w
use JSON -support_by_pp;
use strict;
my @labs = ();  
push (@labs, {id=>'1', title=>'Lab1'});  
push (@labs, {id=>'2', title=>'Lab2'});  
my $json_text = to_json \@labs, {ascii=>1, pretty => 1}; 
print $json_text;

输出:

[
   {
      "title" : "Lab1",
      "id" : "1"
   },
   {
      "title" : "Lab2",
      "id" : "2"
   }
]

答案 1 :(得分:3)

您的语法错误,如果您有

,您会发现
use strict;
use warnings 'all';

位于程序的顶部。我必须每天至少在Stack Overflow上写一遍,但仍然每个人都认为它不适用于他们

use strict;
use warnings 'all';
use v5.10.1;

use JSON;

my @labs;
push @labs, { id => 1, title => 'Lab1' };
push @labs, { id => 2, title => 'Lab2' };

say to_json \@labs, { ascii => 1, pretty => 1 };

输出

[
   {
      "id" : 1,
      "title" : "Lab1"
   },
   {
      "id" : 2,
      "title" : "Lab2"
   }
]