Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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 snow settles gently...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2018-06-24 21:44 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.