Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

loop through JSON data with Perl

by srchulo (Sexton)
on Oct 02, 2011 at 22:04 UTC ( #929190=perlquestion: print w/ replies, xml ) Need Help??
srchulo has asked for the wisdom of the Perl Monks concerning the following question:

So I am needing to parse JSON data. Whenever I have JSON data like this:

{ "items" : [ { "name" : "Theodor Nelson", "id": "_333301" }, { "name": "Morton Heilig", "id": "_13204" } ] }

I can loop through it fine with this code:

use JSON -support_by_pp; my $json = JSON->new->pretty; my $json_object = $json->decode($json_text); for my $item( @{$json_object->{items}} ){ print $item->{name} . "\n"; }

However, whenever my data is like this:

[ { name: "a", value: "1" }, { name: "b", value: "2" }, { name: "c", value: "3" }, { name: "d", value: "4" }, { name: "e", value: "5" } ]

I do not know how to access it because there is no "header" like "items" there was to identify the first set of data by with:  $json_object->{items} and when I just do $json_object, it does not work. Can anyone help?

Comment on loop through JSON data with Perl
Select or Download Code
Re: loop through JSON data with Perl
by Siddartha (Curate) on Oct 02, 2011 at 22:09 UTC
    This should do it:
    for my $item( @{$json_object} ){ print $item->{name} . "\n"; }
    It's just an array that you need to loop through.

      Yeah, I tried this. It doesn't work :/

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2014-08-30 19:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (293 votes), past polls