简体   繁体   中英

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.

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 %]
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM