Is there please a way to make the encode_json
method NOT to put quotes around numbers?
For example I'm using perl 5.10 on CentOS 6.3 (and also ActiveState perl 5.16 on Win 7) and it puts the quotes where it shouldn't:
# perl -MJSON -e 'print encode_json({a => [split(",", "1.2,30")]});'
{"a":["1.2","30"]}
That is, ok yes, it sees the "1.2" and "30" as strings in the code above, but my problem is:
My perl script parses CSV-files and generate HTML-files using Google Charts and the latter are confused by having quotes around number-values (eventhough I told them that the column is of type "numeric").
As a workaround I iterate through my data stracture and replace every number by sprintf "%f", $val
but this results in too many nulls being displayed after each number, which makes the charts correct, but ugly looking:
# perl -e 'printf "%f", "30"'
30.000000
UPDATE:
Yes, adding a zero or multiplying by one seems to work at the first glance:
# perl -MJSON -e 'print encode_json({a => [map {1 * $_} split(",", "1.2,30")]});'
{"a":[1.2,30]}
but in my real script it still doesn't work for the floating numbers.
And you can see the problem I still have at the CLI when using Dumper module too:
# perl -MData::Dumper -e 'print Dumper({a => [map {1.0 * $_} split(",", "1.2,30")]});'
$VAR1 = {
'a' => [
'1.2', # <= THIS IS MY PROBLEM AND CONFUSES GOOGLE CHARTS
30
]
};
Your problem is that although you're correctly converting it to a number, it's getting converted back to a string before you call encode_json. This is because you're calling Data::Dumper on it in a debug statement. If you comment out your call to Data::Dumper, you'll find encode_json outputs the right thing.
e.g. this example shows the JSON object before and after calling Dumper on the object:
$ perl -MData::Dumper -MJSON -e '
my $obj = {a => [map { $_ - 0 } split(",", "1.2,30")]};
print "JSON before: ",encode_json($obj),"\n";
print "Dumper: ",Dumper($obj);
print "JSON after: ",encode_json($obj),"\n";
'
JSON before: {"a":[1.2,30]}
Dumper: $VAR1 = {
'a' => [
'1.2',
30
]
};
JSON after: {"a":["1.2",30]}
as you can see, Dumper actually modifies the object you're dumping, affecting your subsequent encode_json call.
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