Deano Deano - 7 months ago 27
Perl Question

Perl JSON how to get value of key

I have the following json output and i'm trying to get the value of enabled

{
"_id":"sensor1",
"_returned":1,
"_embedded":{
"rh:doc":[
{
"_id":{ },
"enabled":"true"
}
]
}
}


I have tried the following

foreach my $x ( @{$vsConfig}) {
print $x;
}


I'm not sure why its not returning anything, isn't it a hash reference?

Thanks

Answer

Assuming that $vsConfig is a hash ref obtained after the json was decoded:

print $vsConfig->{_embedded}->{'rh:doc'}->[0]->{enabled}

The whole code, including the part that decodes the json:

use strict;
use warnings;
use JSON qw/decode_json/;

my $json = q|
{  
   "_id":"sensor1",
   "_returned":1,
   "_embedded":{  
      "rh:doc":[  
         {  
            "_id":{  },
            "enabled":"true"
         }
      ]
   }
}
|;

my $vsConfig = decode_json( $json );

print $vsConfig->{_embedded}->{'rh:doc'}->[0]->{enabled};
Comments