在Perl中将数字数组转换为json,获取字符串数组 [英] Converting array of numbers to json in perl, getting array of strings

查看:360
本文介绍了在Perl中将数字数组转换为json,获取字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数字数组转换为json:

I'm trying to convert an array of numbers to json:



   $json = to_json("numbers_array" => \@numbers_array);
   print $json;

但是我得到的输出是:


  {"numbers_array" => ["1","2","3"] }

我正在通过使用push()添加元素来构建数组.如何转换为json并保留数字类型,以便输出为:

I'm building up the array by adding elements using push(). How do I convert to json and retain the numeric type, so that the output is:


  {"numbers_array" => [1,2,3]}

谢谢!

推荐答案

来自 JSON文档:

您可以通过对数字进行数字化来将其强制为数字:

You can force the type to be a number by numifying it:

   my $x = "3"; # some variable containing a string
   $x += 0;     # numify it, ensuring it will be dumped as a number
   $x *= 1;     # same thing, the choice is yours.


我会尝试这样的事情:


I would try something like this:

    $json = to_json({numbers_array => [map { $_ + 0 } @numbers_array]});
    print $json;

这篇关于在Perl中将数字数组转换为json,获取字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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