I have an array of hashes that I would like to convert into an un-named JSON array.
If I have an array of hashes which I then try to encode to JSON as such:
my @labs = ();
push (@labs, {id=>'1', title=>'Lab1'});
push (@labs, {id=>'2', title=>'Lab2'});
my $json_text = to_json {\@labs}, {ascii=>1, pretty => 1};
then the resulting JSON looks like:
{
"ARRAY(0x358a18)" : null
}
when in fact I want it to look like:
[
{"title" : "Lab1", "id" : "1"},
{"title" : "Lab2", "id" : "2"}
]
Remove the curly braces from around \@labs - they're converting the array you've created into an anonymous hash before passing it to to_json:
#!/usr/bin/perl -w
use JSON -support_by_pp;
use strict;
my @labs = ();
push (@labs, {id=>'1', title=>'Lab1'});
push (@labs, {id=>'2', title=>'Lab2'});
my $json_text = to_json \@labs, {ascii=>1, pretty => 1};
print $json_text;
output:
[
{
"title" : "Lab1",
"id" : "1"
},
{
"title" : "Lab2",
"id" : "2"
}
]
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