helloworld1234 helloworld1234 - 10 days ago 5
JSON Question

Perl - from JSON to object/ hash

I have to code below:

#!/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";
}

}


When I compile it, it print me the error "Not an ARRAY reference at generator.pl line 12.".

I want to parse the JSON to an object and get data according to the object with the attributes. How can I do it?

I expect after I parse it, I can use to compare string, print, loop it and so on.

Answer

There are no arrays there; it is a hash of hashes.

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";
        }
}