尝试访问JSON数组的内容时出错.
这是我的JSON数组assets.json的内容:
[{"id":1002,"interfaces":[{"ip_addresses":[{"value":"172.16.77.239"}]}]},{"id":1003,"interfaces":[{"ip_addresses":[{"value":"192.168.0.2"}]}]}]
Run Code Online (Sandbox Code Playgroud)
这是我的代码
#!/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";
}
Run Code Online (Sandbox Code Playgroud)
我得到$ item - > {id}的预期输出但是当访问嵌套元素时,我收到错误"Not a HASH reference"
Data::Dumper 你的朋友在这里:
试试这个:
#!/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"}]}]}]
Run Code Online (Sandbox Code Playgroud)
得到:
[
{
'interfaces' => [
{
'ip_addresses' => [
{
'value' => '172.16.77.239'
}
]
}
],
'id' => 1002
},
{
'interfaces' => [
{
'ip_addresses' => [
{
'value' => '192.168.0.2'
}
]
}
],
'id' => 1003
}
]
Run Code Online (Sandbox Code Playgroud)
重要的注意事项 - 你有嵌套数组([]表示数组,{}一个哈希).
所以你可以用以下方法提取你的东西
print $item->{interfaces}->[0]->{ip_addresses}->[0]->{value};
Run Code Online (Sandbox Code Playgroud)
或者作为friedo说明:
请注意,您可以在第一个之后省略 - >运算符,因此
$item->{interfaces}[0]{ip_addresses}[0]{value}也可以使用.