使用JSON.pm跟踪类型

时间:2015-01-15 15:36:47

标签: json perl

说我有以下输入的JSON对象

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

有没有办法用decode_json或from_json知道值的原始类型(数字与字符串)是什么?我知道Perl一般不关心类型,但我需要知道原始类型是什么。我也知道perl在创建JSON对象时会跟踪类型(所以它在创建JSON对象时确实区分了" 21"和21,所以我希望有一种方法可以在保存时保留这些信息解码/'来自它。

我不想把它建立在字段名称的基础上,因为我试图编写一些会在某种程度上使用的东西,并且字段名称可能会改变。

1 个答案:

答案 0 :(得分:4)

使用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
相关问题