Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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?

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://929190]
Approved by Siddartha
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2018-03-17 15:46 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (224 votes). Check out past polls.