Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a perl array of hashes to an unnamed JSON array?

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"}  
]  
like image 490
Vanyel Ashkevron Avatar asked Nov 27 '25 14:11

Vanyel Ashkevron


1 Answers

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"
   }
]
like image 162
Alnitak Avatar answered Nov 30 '25 06:11

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!