Convert array of hashes to json

喜欢而已 提交于 2021-02-07 08:31:11

问题


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"}]}

回答1:


print $j->encode_json({ranks => @ranks});

should be:

print $j->encode_json({ranks => \@ranks});



回答2:


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 } );



回答3:


Try passing the array as a reference.

to_json({ranks => \@ranks},{ascii => 1,pretty => 1});



来源:https://stackoverflow.com/questions/14095410/convert-array-of-hashes-to-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!