Emma Emma - 7 months ago 25
Perl Question

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.

Answer

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.