Perl JSON将所有数字视为字符串

前端之家收集整理的这篇文章主要介绍了Perl JSON将所有数字视为字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为了创建一个与严格打字语言一致的API,我需要修改所有 JSON以返回引用的字符串来代替整数,而不必逐个进行并修改底层数据.

这就是现在生成JSON的方式:

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

什么是一个很好的方式来说,“并引用该$hash中的每个标量”?

解决方法

JSON的两个后端(JSON :: PP和JSON :: XS)都将输出类型基于值的内部存储.解决方案是在数据结构中对非参考标量进行字符串化.

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));

猜你在找的Perl相关文章