loop over JSON using Perl

26,881

Solution 1

Use JSON or JSON::XS to decode the JSON into a Perl structure.

Simple example:

use strict;
use warnings;

use JSON::XS;

my $json = '[{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}]';

my $arrayref = decode_json $json;

foreach my $item( @$arrayref ) { 
    # fields are in $item->{Year}, $item->{Quarter}, etc.
}

Solution 2

You have an array of hashes.

use JSON::XS qw( decode_json );

my $records = decode_json($json_text);
for my $record (@$records) {
   for my $key (keys(%$record)) {
      my $val = $record->{$key};
      say "$key: $val";
    }
}

JSON::XS

Solution 3

Here is a package on CPAN that should do the trick, JSON.pm

Once you parse it, you can treat it like any other Perl reference.

Example

$perl_scalar = $json->decode($json_text)

Documentation

The opposite of encode: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error.

JSON numbers and strings become simple Perl scalars. JSON arrays become Perl arrayrefs and JSON objects become Perl hashrefs. true becomes 1 (JSON::true), false becomes 0 (JSON::false) and null becomes undef.`

Similar stack overflow question: Parsing an array encoded in JSON

Share:
26,881
Mike
Author by

Mike

Updated on July 09, 2022

Comments

  • Mike
    Mike almost 2 years

    I'm a newbie to Perl and want to loop over this JSON data and just print it out to the screen.

    How can I do that?

    $arr = '[{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}]';