Emma
Emma

Reputation: 53

decode list of JSON objects to array of hashes in perl

I'm a newbie to Perl,I want to parse the following JSON into array of hashes,(map method will be preferred)

[
    {   "name" : "Theodor Nelson",
        "id": "_333301",
        "address": "Hello_world"
    },
    {   "name": "Morton Heilig",
        "id": "_13204",
        "address": "Welcome"
     }
    ]

then wants to print only "

name

and

id

's values in foreach loop. any kind of help will be appreciated.

Upvotes: 3

Views: 6426

Answers (3)

Shaista
Shaista

Reputation: 157

you can simply do like

use JSON qw(encode_json decode_json);

my $JSON = [{   "name" : "Theodor Nelson",
        "id": "_333301",
        "address": "Hello_world },
        {   "name": "Morton Heilig",
        "id": "_13204",
        "address": "Welcome"}]

my $decoded = decode_json $JSON;

return template 'yourtemplate', {
    options =>  $decoded,
        ..,
        ..}

and in view file you can access it as option.id and option.name or option.address or whatever is required in FOREACH loop.

Upvotes: 0

Sebastian
Sebastian

Reputation: 2550

use JSON qw(from_json);

# The JSON module likes to die on errors
my $json_data = eval { return from_json($json); };
die "$@ while reading JSON" if $@; # Replace by your error handling
die "JSON top level is no array" unless ref($json_data) eq 'ARRAY'; # Replace by your error handling

for my $hashref (@{$json_data}) {
    print $hashref->{name}."\n";
    print $hashref->{id}."\n";
}

The error handling is obviously optional depending on your usage case. One-time or manual scripts may just die while production-level scripts should have a proper error handling.

The JSON module is a wrapper for JSON::PP and JSON::XS. It selects the module available on the local system. JSON::XS is faster, but might not be installed. JSON::PP is pure Perl (no external C/C++ libraries) and part of the Perl core.

The for line dereferences the Array-reference representing your top level JSON array. Each item should be a Hash-reference. Follow the links for more information on each topic.

Upvotes: 1

ikegami
ikegami

Reputation: 385725

use JSON::XS qw( decode_json );

my $data = decode_json($json);

$template->process(..., { data => $data }, ...)
   or die(...);

Template:

[% FOREACH rec IN data %]
   [% rec.id %]: [% rec.name %]
[% END %]

Upvotes: 0

Related Questions