2010-09-12 44 views
6

以下perl代码已经写入以解析JSON中的数组。但数组返回的长度为1,我无法正确地迭代它。所以问题是我无法使用返回的数组。通过perl解析以JSON编码的数组

#!/usr/bin/perl 
use strict; 

my $json_text = '[ {"name" : "abc", "text" : "text1"}, {"name" : "xyz", "text" : "text2"} ]'; 

use JSON; 
use Data::Dumper::Names; 

my @decoded_json = decode_json($json_text); 
print Dumper(@decoded_json), length(@decoded_json), "\n"; 

输出谈到:

$VAR1 = [ 
    { 
     'text' => 'text1', 
     'name' => 'abc' 
     }, 
     { 
     'text' => 'text2', 
     'name' => 'xyz' 
     } 
    ]; 
1 

回答

16

decode_json function返回一个数组引用,而不是一个列表。您必须取消对它的引用,以获取列表:

my @decoded_json = @{decode_json($json_text)}; 

您可能需要阅读perldoc perlreftutperldoc perlref

+0

解引用有点帮助。现在我可以迭代返回的数组了。但我仍然得到阵列的长度= 1 – 2010-09-12 14:21:01

+0

我的不好。正在使用长度(@decoded_json)来获得阵列的长度! – 2010-09-12 14:26:02

1

关于JSON,你可能想确保你安装JSON :: XS模块,因为它是更快,比JSON模块包含的纯perl实现更稳定。 JSON模块在可用时将自动使用JSON :: XS。