使用 JSON.pm 跟踪类型 [英] keeping track of type with JSON.pm

查看:39
本文介绍了使用 JSON.pm 跟踪类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下输入的 JSON 对象

say i have the following inputted JSON object

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

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

is there any way with decode_json or from_json to know what the original type was (number verses string) of the values? I know Perl generally doesnt care about type, but I have a need to know what the original type was. I also know that perl does keep track of the type when creating a JSON object (so it does distinguish between "21" and 21 when creating a JSON object, so Im hoping there is a way to keep that information when decoding/'from'ming it.

我不想基于字段名称,因为我试图编写一些通用的东西,并且字段名称可能会改变.

I don't want to base it on the field name, because im trying to write something that will be used somewhat generically, and fieldnames could change.

推荐答案

使用 JSON::XS 时,标量中值的类型与文档中的值类型匹配.

When using JSON::XS, the type of the value in the scalar matches the type of the value in the document.

$ 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 将非常大的数字存储为字符串以避免丢失精度.

As you can see, the fourth scalar is an exception when using JSON::XS. JSON::XS stores very large numbers as strings to avoid loosing precision.

您使用 JSON::PP 得到类似的结果:

You get similar results with JSON::PP:

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

这篇关于使用 JSON.pm 跟踪类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆