Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
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?

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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://929190]
Approved by Siddartha
help
Chatterbox?
[Corion]: Hehe - $work is a place where we have lots of (money) accounts, and lots of journals where every transaction is recorded. But our HR system where the accounts of hours worked and vacation days taken are stored, there is no real account of who changed ...
[Corion]: ... that balance, and when. And it seems to me that they somehow really messed up the database since the start of the year and have been frantically adding and subtracting numbers from the totals, but without trace ;)

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2018-01-23 16:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How did you see in the new year?










    Results (249 votes). Check out past polls.

    Notices?