4

perl version 5.18

I am having an issue with the perl JSON encoder and putting quotes around a float.

see sample code:

use JSON;
use Data::Dumper;

my $float = 1.2;

my $t = {
  float => $float
};  

my $json1 = encode_json($t);
print Dumper $t;
my $json2 = encode_json($t);
print $json1 . "\n";
print $json2 . "\n";

Output:

$VAR1 = {
          'float' => '1.2',
          'integer' => 1
        };
{"float":1.2,"integer":1}
{"float":"1.2","integer":1}

As you can see after using Dumper the JSON encoder adds the quotes. Any ideas why this would happen?

Not in the sample code above, but in production, I can not remove the quotes unless I add .01. Even *= *1 does not work.

clintonm9
  • 181
  • 1
  • 1
  • 6
  • 1
    I can't reproduce the problem with Perl 5.26.0 / Data::Dumper 2.167 / JSON 2.97001. Possibly this is a bug that has since been fixed. – Quentin Jul 19 '18 at 19:33

1 Answers1

5

This is an "expected" strange behaviour which happens (in old versions of perl) due to how perl handles variables. Each variable may have number and string representations, which may be stored in memory simultaneously. In most cases perl will use proper representation depending on the context.

When you assign $t a float value, only the number representation is stored. This is why first encode_json behaves as expected. Then dumping the variable creates string representation which is also stored in memory. It does not remove number representation, but in the second call encode_json cannot tell which representation to use and takes string.

Once again perl 5.18 is 5 years old now, and this behaviour was fixed in newer versions on perl, so my suggestion is to use recent versions.

See https://www.perlmonks.org/?node_id=909619 for detailed discussion.

Sergey Martynov
  • 426
  • 4
  • 9