尝试访问 JSON 数组的内容时出现错误。
这是我的 JSON 数组 assets.json 的内容:
[{"id":1002,"interfaces":[{"ip_addresses":[{"value":"172.16.77.239"}]}]},{"id":1003,"interfaces":[{"ip_addresses":[{"value":"192.168.0.2"}]}]}]
这是我的代码
#!/usr/bin/perl
use strict;
use warnings;
use JSON::XS;
use File::Slurp;
my $json_source = "assets.json";
my $json = read_file( $json_source ) ;
my $json_array = decode_json $json;
foreach my $item( @$json_array ) {
print $item->{id};
print "\n";
print $item->{interfaces}->{ip_addresses}->{value};
print "\n\n";
}
我得到了 $item->{id} 的预期输出,但是在访问嵌套元素时
我收到错误“不是 HASH 引用”
最佳答案
Data::Dumper
你的 friend 在这里吗:
试试这个:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON::XS;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Terse = 1;
my $json_array = decode_json ( do { local $/; <DATA> } );
print Dumper $json_array;
__DATA__
[{"id":1002,"interfaces":[{"ip_addresses":[{"value":"172.16.77.239"}]}]},{"id":1003,"interfaces":[{"ip_addresses":[{"value":"192.168.0.2"}]}]}]
给出:
[
{
'interfaces' => [
{
'ip_addresses' => [
{
'value' => '172.16.77.239'
}
]
}
],
'id' => 1002
},
{
'interfaces' => [
{
'ip_addresses' => [
{
'value' => '192.168.0.2'
}
]
}
],
'id' => 1003
}
]
重要的一点——你有嵌套的数组(
[]
表示数组,{}
是一个散列)。所以你可以用以下方法提取你的东西:
print $item->{interfaces}->[0]->{ip_addresses}->[0]->{value};
或作为 friedo笔记:
Note that you may omit the -> operator after the first one, so
$item->{interfaces}[0]{ip_addresses}[0]{value}
will also work.
关于json - 在 Perl 中访问嵌套的 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737301/