我真的很难理解如何导航JSON对象。我正在使用JSON.pm,我正在我的桌子上试图访问每个“name”参数并存储它的“values”数组的第一个索引。
我无法理解基本结构,数组/哈希引用如何工作,以及如何迭代它们以访问我需要的值。如果有人可以帮我指出正确的方向......我现在很迷茫/困惑。
这是我正在使用的示例数据(Facebook开放图形对象)。
{
"data": [
{
"id": "219127134886593/insights/page_impressions/week",
"name": "page_impressions",
"period": "week",
"values": [
{
"value": 31600,
"end_time": "2013-03-07T08:00:00+0000"
},
{
"value": 31979,
"end_time": "2013-03-08T08:00:00+0000"
},
{
"value": 29517,
"end_time": "2013-03-09T08:00:00+0000"
}
],
"title": "Weekly Total Impressions",
"description": "Weekly The number of impressions seen of any content associated with your Page. (Total Count)"
},
{
"id": "219127134886593/insights/page_impressions_organic/week",
"name": "page_impressions_organic",
"period": "week",
"values": [
{
"value": 23587,
"end_time": "2013-03-07T08:00:00+0000"
},
{
"value": 23858,
"end_time": "2013-03-08T08:00:00+0000"
},
{
"value": 22813,
"end_time": "2013-03-09T08:00:00+0000"
}
],
"title": "Weekly Organic impressions",
"description": "Weekly The number of times your posts were seen in News Feed or ticker or on visits to your Page. These impressions can be by people who have liked your Page and people who haven't. (Total Count)"
},
],
"paging": {
"previous": "https://graph.facebook.com/219127134886593/insights/page_impressions,page_impressions_organic,page_impressions_viral,page_storytellers/week?since=1362383320&until=1362642520",
"next": "https://graph.facebook.com/219127134886593/insights/page_impressions,page_impressions_organic,page_impressions_viral,page_storytellers/week?since=1362901720&until=1363160920"
}
}
这就是我正在努力访问不同的元素:
foreach my $data ( $decoded_json->{data} ) {
foreach my $item ( @$data ) {
$list{ $item->{'name'} } = $item->{'values'};
print "Value 3: @($item->{'values'})[3]\n";
}
}
答案 0 :(得分:1)
for my $item (@{ $decoded_json->{data} }) {
$list{ $item->{'name'} } = $item->{'values'};
print "Value 4: $item->{'values'}[3]\n";
}
有关参考资料的详情,请参阅http://p3rl.org/REF。
答案 1 :(得分:0)
成功!
foreach my $data ( $decoded_json->{data} ) {
foreach my $item ( @$data ) {
$list{ $item->{'name'} } = ${ $item->{'values'} }[1]->{'value'};
print "Name: $item->{'name'}\n";
print "Value 3: ${ $item->{'values'} }[1]->{'value'}\n";
}
}
谢谢你: dispersiondesign.com thegeekstuff.com
谢谢大家,凝聚了:
foreach my $item ( @{ $decoded_json->{data} } ) {
$list{ $item->{'name'} } = $item->{'values'}->[1]->{'value'};
print "Name: $item->{'name'}\n";
print "Value 3: $item->{'values'}->[1]->{'value'}\n";
}