2016-04-25 48 views
1

我是新手到Perl中,我想以下JSON解析成散列的陣列,(地圖方法將是優選的)解碼對象列表到散列的陣列在Perl

[ 
    { "name" : "Theodor Nelson", 
     "id": "_333301", 
     "address": "Hello_world" 
    }, 
    { "name": "Morton Heilig", 
     "id": "_13204", 
     "address": "Welcome" 
    } 
    ] 

然後想要僅打印「

ID

在foreach循環中的值。 任何形式的幫助將不勝感激。

+1

您應該查看[JSON :: XS](https://metacpan.org/pod/JSON::XS)模塊。有很多例子可以描述你想要做什麼。 '我的$ aref = decode_json($ str);打印「$ _-> {id}:$ _-> {name} \ n」爲@ $ aref;' –

+0

可以告訴我如何在視圖文件中打印值? – Emma

+0

我不明白你在問什麼。 –

回答

0

,你可以簡單地做喜歡

use JSON qw(encode_json decode_json); 

my $JSON = [{ "name" : "Theodor Nelson", 
     "id": "_333301", 
     "address": "Hello_world }, 
     { "name": "Morton Heilig", 
     "id": "_13204", 
     "address": "Welcome"}] 

my $decoded = decode_json $JSON; 

return template 'yourtemplate', { 
    options => $decoded, 
     .., 
     ..} 

,並在視圖文件,您可以訪問它爲option.idoption.nameoption.address或任何需要在foreach循環。

+0

這就是我所要求的,謝謝Luna – Emma

+0

不客氣:) – Shaista

0
use JSON::XS qw(decode_json); 

my $data = decode_json($json); 

$template->process(..., { data => $data }, ...) 
    or die(...); 

模板:

[% FOREACH rec IN data %] 
    [% rec.id %]: [% rec.name %] 
[% END %] 
0
use JSON qw(from_json); 

# The JSON module likes to die on errors 
my $json_data = eval { return from_json($json); }; 
die "[email protected] while reading JSON" if [email protected]; # Replace by your error handling 
die "JSON top level is no array" unless ref($json_data) eq 'ARRAY'; # Replace by your error handling 

for my $hashref (@{$json_data}) { 
    print $hashref->{name}."\n"; 
    print $hashref->{id}."\n"; 
} 

錯誤處理顯然是可選根據您的使用情況。一次性或手動腳本可能會死亡,而生產級腳本應該具有適當的錯誤處理。

JSON模塊是JSON::PPJSON::XS的包裝。它選擇本地系統上可用的模塊。 JSON :: XS速度更快,但可能未安裝。 JSON :: PP是純Perl(沒有外部C/C++庫)和Perl核心的一部分。

for line dereferences the Array-reference代表您的頂級JSON數組。每個項目應該是哈希引用。按照鏈接瞭解每個主題的更多信息。