在Perl中访问嵌套的JSON元素 [英] Accessing nested JSON elements in Perl

查看:82
本文介绍了在Perl中访问嵌套的JSON元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试访问JSON数组的内容时出现错误.

I get an error when attempting to access the contents of my JSON array.

这是我的JSON数组asset.json的内容:

Here is the contents of my JSON array 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}的预期输出 我收到错误消息不是哈希引用"

I get the expected output for $item->{id} but when accessing the nested element I get the error "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"}]}]}]

赠予:

[
  {
    'interfaces' => [
      {
        'ip_addresses' => [
          {
            'value' => '172.16.77.239'
          }
        ]
      }
    ],
    'id' => 1002
  },
  {
    'interfaces' => [
      {
        'ip_addresses' => [
          {
            'value' => '192.168.0.2'
          }
        ]
      }
    ],
    'id' => 1003
  }
]

重要注意事项-您具有嵌套数组([]表示数组,{}表示哈希).

Important point of note - you have nested arrays (the [] denotes array, the {} a hash).

因此,您可以使用以下方法提取您的内容:

So you can extract your thing with:

print $item->{interfaces}->[0]->{ip_addresses}->[0]->{value};

或作为 friedo 注释:

请注意,您可以在第一个运算符之后省略->运算符,因此$item->{interfaces}[0]{ip_addresses}[0]{value}也将起作用.

这篇关于在Perl中访问嵌套的JSON元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆