I want to convert an array of hashes that I create like this:
while(...)
{
...
push(@ranks, {id => $id, time => $time});
}
To JSON:
use JSON;
$j = new JSON;
print $j->encode_json({ranks => @ranks});
But it is outputting this:
{"ranks":{"time":"3","id":"tiago"},
"HASH(0x905bf70)":{"time":"10","id":"bla"}}
As you can see it isnt able to write on of the hashes and there's no array...
I would like to output a JSON string that looked like this:
{"ranks":[{"time":"3","id":"tiago"},
{"time":"40","id":"fhddhf"},
{"time":"10","id":"bla"}]}
All of these are the same:
ranks => @ranks
'ranks', @ranks
'ranks', $ranks[0], $ranks[1], $ranks[2]
ranks => $ranks[0], $ranks[1] => $ranks[2]
So you're creating a hash with two elements when you mean to create a hash with one element.
You tried to use an array as a hash value, but hash values can only be scalars. It is common, however, to use a reference to an array as a hash value since references are scalars, and this is what encode_json
expects.
print $j->encode_json( { ranks => @ranks } );
should be
print $j->encode_json( { ranks => \@ranks } );
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