mr007619 has asked for the wisdom of the Perl Monks concerning the following question:

So I'm having an issue with interpreting JSON data and documentation I've been reading has me admittedly confused and it seems like this is a pretty much a newbie/trivial question. Below is my code and the issue I'm having:

$request = HTTP::Request->new(GET => 'https://xxxx'); $ua = LWP::UserAgent->new; $response = $ua->request($request); $decodejs = decode_json $response->content; print Dumper $decodejs;

The output of this gives me something like this:

$VAR1 = { 'lbvserver' => [ {, 'name' => 'name1', 'ipv46' => '192.168.1.1', }, { 'name' => 'name2', 'ipv46' => '10.1.1.1', } and so on.

I'm trying to directly grab name and IP values as an instance and having the worst time figuring out the correct way to do it. Any help or direct reference to a page I should be reading would be greatly appreciated.

Replies are listed 'Best First'.
Re: Attempting to interpret JSON data
by moritz (Cardinal) on May 16, 2012 at 19:47 UTC
    As a simple rule, for every { in the Data::Dumper output you need a { for dereferencing, and for every [ in the dumper output you need a [ for dereferencing:
    # $VAR1 = { 'lbvserver' => [ {, 'name' => 'name1', ' # ^ ^ ^ my $name = $decode_json->{lbvserver}[0]{name}; # ^ ^ ^

    perlreftut and maybe perldsc should teach you enough to figure it out.

      One last question here after finally starting to understand array and hash references. So since this is a mix of both, is the best way to loop through each array of hashes to grab the count of array elements as such

      $count = -1; foreach $elem (@{$decodejs->{'lbvserver'}}) { $count++; } $num = 0; while ($num <= $count) { print "$decodejs->{'lbvserver'}[$num]{'valueIwant'}\n"; $num++ }

        Maybe simply

        for my $elem (@{$decodejs->{lbvserver}}) { print "$elem->{valueIwant}\n"; }
Re: Attempting to interpret JSON data
by Anonymous Monk on May 16, 2012 at 19:51 UTC
    See also JSON::Path, its like xpath or jquery for json