Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of hashes to json

Tags:

perl

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"}]}
like image 948
Tiago Costa Avatar asked Dec 05 '22 13:12

Tiago Costa


1 Answers

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 } );
like image 160
ikegami Avatar answered Dec 19 '22 19:12

ikegami