Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
We don't bite newbies here... much
 
PerlMonks  

Attempting to interpret JSON data

by mr007619 (Novice)
on May 16, 2012 at 19:42 UTC ( #970900=perlquestion: print w/ replies, xml ) Need Help??
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.

Comment on Attempting to interpret JSON data
Download Code
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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://970900]
Approved by Eliya
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2013-06-19 07:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How many continents have you visited?









    Results (644 votes), past polls