2012-06-01 83 views
0

我有這個print STDERR Dumper $data
$VAR1 = '{
"url_date":null,
"footer":null,"id":"18",
"authors":[
{"initials":"B.","last_name":"Best","has":0,"id":12},
{"initials":"D.","last_name":"Dough","has":1,"id":10},
{"initials":"F.","last_name":"Fuss","has":0,"id":15,}
],
"url_headline":null,
"headline":"test"}';

我想訪問麪糰會怎麼做呢?
我試過print STDERR Dumper $data.authors[1].last_name但有語法錯誤。如何訪問JSON對象值

第二個嘗試
use JSON::XS qw(decode_json);
my $coder = JSON::XS->new->utf8->pretty->allow_nonref;
my $p = $coder->decode ($.data);

回答

2

最好的辦法是到字符串JSON模塊首先解碼成Perl散列引用,然後使用普通Perl的哈希訪問語法$data->{"authors"}[1]{"last_name"}

4

你有一個字符串。該字符串包含的是有效的JSON和有效的YAML。您需要解析JSON,最好的方法是使用現有的解析器,如JSON::XS

use JSON::XS qw(decode_json); 
my $data = decode_json($data_json); 
$data->{authors}[1]{last_name} 
+0

我有一個語法錯誤...我更新了代碼,請參閱第二次嘗試。 'print STDERR Dumper%{$ p};'給了我全部的$ data信息,但是當我做'print STDERR Dumper%{$ p} - > authors [1] {last_name};'我也有語法錯誤.. – mamesaye

+0

這是因爲你沒有使用我發佈的內容。 – ikegami

+0

我沒有嘗試過你發佈的內容,並在第78行附近出現了'語法錯誤 - > authors [「'然後我什麼時候到了JSON :: XS頁面,發現第二次嘗試並且也有語法錯誤..什麼是問題? – mamesaye