Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array of numbers to json in perl, getting array of strings

Tags:

json

perl

I'm trying to convert an array of numbers to json:


   $json = to_json("numbers_array" => \@numbers_array);
   print $json;

but the output I'm getting is:

  {"numbers_array" => ["1","2","3"] }

I'm building up the array by adding elements using push(). How do I convert to json and retain the numeric type, so that the output is:

  {"numbers_array" => [1,2,3]}

Thanks!

like image 333
Vijay Boyapati Avatar asked Feb 16 '23 17:02

Vijay Boyapati


2 Answers

From the JSON documentation:


You can force the type to be a number by numifying it:

   my $x = "3"; # some variable containing a string
   $x += 0;     # numify it, ensuring it will be dumped as a number
   $x *= 1;     # same thing, the choice is yours.

I would try something like this:

    $json = to_json({numbers_array => [map { $_ + 0 } @numbers_array]});
    print $json;
like image 81
hmatt1 Avatar answered Feb 18 '23 05:02

hmatt1


In addition to earlier answers: it's not a question of the definition of your data but of usage.

From the JSON::XS pod:

JSON::XS will encode […] scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value

Consider this piece of code:

use JSON::XS;
my $numbers = [123,124,125];
print "A number: $numbers->[1]\n";            #<- use 2nd entry in string context.
print JSON::XS->new->encode ($numbers)."\n";

It prints:

A number: 124
[123,"124",125]

Would you have expected that number 124 be encoded as string? Beware!

(I learned that the hard way chasing a heisenbug that only showed up when I had some debug logging active.)

like image 34
Rubyd Avatar answered Feb 18 '23 05:02

Rubyd