Perl JSON treats all numbers as a string

To create an API that matches strict input languages, I need to change all JSON to return quoted strings instead of integers, without going one by one and changing the underlying data.

This is how JSON is now created:

  my $json = JSON->new->allow_nonref->allow_unknown->allow_blessed->utf8;
  $output = $json->encode($hash);

What would be a good way to say: "And quote every scalar in this hash file?"

+4
source share
1 answer

Both JSON servers (JSON :: PP and JSON :: XS) base the output type on the internal memory of the value. The solution is to reinforce the incorrect scalars in your data structure.

sub recursive_inplace_stringification {
   my $reftype = ref($_[0]);
   if (!length($reftype)) {
      $_[0] = "$_[0]" if defined($_[0]);
   }
   elsif ($reftype eq 'ARRAY') {
      recursive_inplace_stringification($_) for @{ $_[0] };
   }
   elsif ($reftype eq 'HASH') {
      recursive_inplace_stringification($_) for values %{ $_[0] };
   }
   else {
      die("Unsupported reference to $reftype\n");
   }
}

# Convert numbers to strings.
recursive_inplace_stringification($hash);

# Convert to JSON.
my $json = JSON->new->allow_nonref->utf8->encode($hash);

, allow_unknown allow_blessed, recursive_inplace_stringification (, JSON:: PP, ), recursive_inplace_stringification:

# Convert objects to strings.
$hash = JSON->new->allow_nonref->decode(
   JSON->new->allow_nonref->allow_unknown->allow_blessed->encode(
      $hash));
+6

All Articles