Type tracking using JSON.pm

let's say I have the following JSON object entered

{
   "field1": 21,
   "field2": "21",
   "field3": "hello"
}

Is there any way with decode_json or from_json to find out what the original type (string of numeric strings) of the values ​​is? I know Perl doesn't care about the type at all, but I need to know what the original type is. I also know that perl keeps track of the type when creating the JSON object (therefore, it distinguishes between "21" and "21" when creating the JSON object, so Im hopes there is a way to save this information when decoding / "from", ming it.

I do not want to base it on the name of the field, because I'm trying to write something that will be used somewhat in a general way, and field names can change.

0
source share
1 answer

JSON:: XS .

$ perl -e'
   use strict;
   use warnings;

   use B        qw( svref_2object SVf_IOK SVf_NOK SVf_POK );
   use JSON::XS qw( decode_json );

   my $data = decode_json(q{[ "4", 4, 4.0, 20000000000000000000 ]});

   for my $i (0..$#$data) {
      my $sv = svref_2object(\( $data->[$i] ));
      my $flags = $sv->FLAGS;
      printf("Scalar %s has %s\n",
         $i,
         join(",",
            $flags & SVf_POK ? "PV" : (),
            $flags & SVf_IOK ? "IV" : (),
            $flags & SVf_NOK ? "NV" : (),
         ),
      );
   }
'
Scalar 0 has PV
Scalar 1 has IV
Scalar 2 has NV
Scalar 3 has PV

, JSON:: XS. JSON:: XS , .

JSON:: PP:

Scalar 0 has PV
Scalar 1 has IV
Scalar 2 has NV
Scalar 3 has NV
+4

Source: https://habr.com/ru/post/1693538/


All Articles