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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With