Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over JSON using Perl [duplicate]

Tags:

json

perl

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}]';
like image 609
Mike Avatar asked Nov 29 '22 16:11

Mike


1 Answers

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.
}
like image 140
friedo Avatar answered Dec 06 '22 07:12

friedo