2010-09-12 68 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。