How to access data stored in Hash
12,509
Solution 1
The return value of decode
isn't a hash and you shouldn't be assigning it to a %hash
-- when you do, you destroy its value. It's a hash reference and should be assigned to a scalar. Read perlreftut.
Solution 2
As the decode
method actually returns a reference to hash, the proper way to assign would be:
%perl = %{ $coder->decode ($json) };
That said, to get the data from the hash, you can use the each builtin or loop over its keys and retrieve the values by subscripting.
while (my ($key, $value) = each %perl) {
print "$key = $value\n";
}
for my $key (keys %perl) {
print "$key = $perl{$key}\n";
}
Solution 3
JSON::XS->decode returns a reference to an array or a hash. To do what you are trying to do you would have to do this:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
$perl = $coder->decode ($json);
print %{$perl};
In other words, you'll have to dereference the hash when using it.
Author by
Jay Gridley
Updated on June 30, 2022Comments
-
Jay Gridley almost 2 years
I have this code:
$coder = JSON::XS->new->utf8->pretty->allow_nonref; %perl = $coder->decode ($json);
When I write
print %perl
variable it says HASH(0x9e04db0). How can I access data in this HASH? -
Jay Gridley about 14 yearsOK, I figured out that print keys %{$perl} gets me key from Hash, but print values %{$perl} gets me another Hash reference. So I stored this reference in new scalar variable, but when I try to access data in this Hash, it gives me nothing. $json = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S"}}}'; $coder = JSON::XS->new->utf8->pretty->allow_nonref; $perl = $coder->decode ($json); print keys %{$perl},"\n"; #give me glossary print values %{$perl},"\n"; #give me HASH(address) my $val = values %{$perl}; # store address print keys %{$val}; ##give nothing -- title expected