json - 在 Perl 中访问嵌套的 JSON 元素

标签 json perl

尝试访问 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/

相关文章:

regex - Windows 和 Linux 中的 Perl 正则表达式问题

perl - 您是否应该检查 Getopt::Long::GetOptions 的返回码?

json - YAML 和 JSON 有什么区别?

json - 如何在网站页面上显示 Shopify 购物车值(Shopify 网站之外)

json - 如何使用 Serde 从 JSON 命名值而不是数组中(反)序列化元组结构?

regex - Perl正则表达式匹配来自磁力链接的infohash

regex - 使用 perl 替换除最后一次出现的所有内容

php - JSON 或 XML 在 iOS 上性能更好吗?

javascript - 获取 XMLHttpRequest 无法在第二次 api 调用 Instagram 上加载

perl - 如何将所有 CPAN 模块更新到最新版本?