Perl - 从JSON到object / hash

时间:2016-11-28 08:10:23

标签: json perl

我必须在下面编写代码:

#!/usr/intel/bin/perl

use strict;
use warnings;

use JSON::XS;

my $json = '{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}';

my $arrayref = decode_json $json;

for my $array(@$arrayref){
        for my $key (keys(%$array)){
                my $val = $array->{$key};
                print "$key: $val\n";
        }

}

当我编译它时,它会打印错误“在generator.pl第12行不是ARRAY引用。”。

我想将JSON解析为一个对象,并根据具有属性的对象获取数据。我该怎么办?

我希望在解析之后,我可以用来比较字符串,打印,循环它等等。

2 个答案:

答案 0 :(得分:4)

它不是数组引用,它是哈希引用:

#!/usr/intel/bin/perl

use strict;
use warnings;

use JSON::XS;
use Data::Dumper;

my $json = '{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}';

my $arrayref = decode_json $json;

print Data::Dumper->Dump([$arrayref], [qw(arrayref)]);

输出:

$arrayref = {
              'Object2' => {
                             'Quarter' => 'Q4',
                             'Year' => '2012',
                             'Amount' => 500,
                             'DataType' => 'Other 2',
                             'Environment' => 'MIKE'
                           },
              'Object1' => {
                             'Amount' => 125,
                             'DataType' => 'Other 3',
                             'Year' => '2012',
                             'Environment' => 'STEVE',
                             'Quarter' => 'Q3'
                           }
            };

答案 1 :(得分:2)

那里没有阵列;它是哈希的散列。

my $hashref = decode_json $json;

for my $object_name (sort keys %$hashref){
        print "In $object_name:\n";
        for my $key (sort keys %{ $hashref->{$object_name} }){
                my $val = $hashref->{$object_name}{$key};
                print "$key: $val\n";
        }
}