Reputation: 4251
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"}]}
Upvotes: 4
Views: 12552
Reputation: 385725
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 } );
Upvotes: 7
Reputation: 3498
print $j->encode_json({ranks => @ranks});
should be:
print $j->encode_json({ranks => \@ranks});
Upvotes: 6
Reputation: 2661
Try passing the array as a reference.
to_json({ranks => \@ranks},{ascii => 1,pretty => 1});
Upvotes: 3