#!/usr/bin/perl
use strict;
use warnings;
use feature qw/ say /;
use Data::Dumper;
use JSON;
my $data = qq#
{
"items" : [
{ "name" : "Theodor Nelson",
"id": "_333301"
},
{ "name": "Morton Heilig",
"id": "_13204"
}
]
}
#;
my $obj = from_json( $data );
my @names;
my @ids;
say Dumper $obj;
# $obj is an anonymous hash with one key, 'items'
my @items = @{ $obj->{'items'} };
# The value of the key 'items' is an anonymous array.
# Here for simplicity we copy it into a new array.
# We access it by deferencing it using @{ }
foreach my $item ( @items ) {
# Each element of the anonymous array is a hashref.
# So $item is a hashref, not a scalar
my $name = $item->{'name'};
my $id = $item->{'name'};
push @names, $name;
push @ids, $id;
}
say 'Names: ' . join ', ', @names;
say 'IDs: ' . join ', ', @ids;
__END__
####
#!/usr/bin/perl
use strict;
use warnings;
use feature qw/ say /;
use Data::Dumper;
use JSON;
my $data = qq#
{
"items" : [
{ "name" : "Theodor Nelson",
"id": "_333301"
},
{ "name": "Morton Heilig",
"id": "_13204"
}
]
}
#;
my $obj = from_json( $data );
my %names;
$names{ $_->{'id'} } = $_->{'name'} for @{ $obj->{'items'} };
while ( my( $id, $name ) = each %names ) {
say "$id: $name";
}
__END__
####
$ perl 651544-2.pl
_13204: Morton Heilig
_333301: Theodor Nelson
$
####
#!/usr/bin/perl
use strict;
use warnings;
use feature qw/ say /;
use Data::Dumper;
use JSON;
my $data = qq#
{
"items" : [
{ "name" : "Theodor Nelson",
"id": "_333301"
},
{ "name": "Morton Heilig",
"id": "_13204"
}
]
}
#;
my $obj = from_json( $data );
say ${ $obj->{'items'}->[1] }{'name'};
# ^ ^ ^ ^ ^ ^
# | | | | | |
# | is an arrayref | -----------
# | | |
# | first element of which is a hash |
# | |
# the variable is value of the 'name' key
__END__