nilesOien has asked for the wisdom of the Perl Monks concerning the following question:

We have perl code that used to produce JSON that looked, in part, something like this :

 "count" : "3"

And then after installing a new module via cpanm, which caused a lot of updates, it produced JSON that looks like this :

 "count" : 3

Notice that there are no quotes around the number now. This caused much confusion as it caused the downstream parser of the JSON to choke. After a lot of chasing, it seems like after the update, if you do math with a hash reference, it changes the type of the variable from a string to a number, even if the hash reference is not used to store the output. It's probably best illustrated by the script below.

#!/usr/bin/perl use warnings; use strict; use JSON; my $json = JSON->new->allow_nonref->allow_unknown->allow_blessed->pretty(1); # Take the string "1", put it in a hash, encode as JSON and print. # This prints : # { # "num" : "1" # } # The quotes around the number 1 are significant, they mean # that perl treats the has entry as a string (not surprising). my $data1; $data1->{"num"} = "1"; my $body1 = $json->encode($data1); print $body1; # Take the number (not string!) 2, put in in a hash, # encode as JSON and print. # This prints : # { # "num" : 2 # } # There are no quotes around the 2, since perl # treats it as a number. # Again, not surprising. my $data2; $data2->{"num"} = 2; my $body2 = $json->encode($data2); print $body2; # Take the string "3", put it in a hash, do some math with it, # then encode as JSON and print. # This prints : # { # "num" : 3 # } # So, perl is treating the hash entry, which was a sting, # as a number, because using it to do math seems to cause # perl to treat it as a number in the JSON. # Not sure if the hash entry changed type, or had some internal # flag set on it, but this is surprising, and this behavior # seems to be a departure from the past. # Did something change in the JSON module? my $data3; $data3->{"num"} = "3"; my $addr = $data3->{"num"} + 7; my $body3 = $json->encode($data3); print $body3; exit 0;

We are running on CentOS 6.8 with this perl :

/usr/bin/perl --version This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi

What changed? Is it the JSON module? It seems like it used to make a number out of the string in a temporary way, do math with it, and then discard that number, but now it actually changes the type of the hash reference. And is this new way the desired behavior? Is this change documented? It was hard to figure out in our case.

Thanks, all - Niles Oien.