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!
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;
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.)
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