perl json编码将数字转换为字符串
我正在尝试对perl嵌套哈希进行编码,并将其发送到某个web应用程序。 json编码器以某种方式将数字或浮点数转换为字符串。 web应用程序将数据视为字符串,无法绘制图表。我可以在web应用程序中添加代码,将它们转换回数字,但我正在寻找更好的解决方案,首先不要将数字作为字符串 代码如下:perl json编码将数字转换为字符串,json,perl,cgi,encode,Json,Perl,Cgi,Encode,我正在尝试对perl嵌套哈希进行编码,并将其发送到某个web应用程序。 json编码器以某种方式将数字或浮点数转换为字符串。 web应用程序将数据视为字符串,无法绘制图表。我可以在web应用程序中添加代码,将它们转换回数字,但我正在寻找更好的解决方案,首先不要将数字作为字符串 代码如下: use strict; use warnings; use CGI qw/param/; use JSON::XS; my $json_obj = JSON::XS->new->allow_nonr
use strict;
use warnings;
use CGI qw/param/;
use JSON::XS;
my $json_obj = JSON::XS->new->allow_nonref;
## Build some Perl data
my %perl_data;
$perl_data{'numbers'}{'nested'} = [qw/1 -2 4 2 5 6/] ;
$perl_data{'mix'}{'AnotherLevel'} = [qw/null "Temp" 4 2 5 6/] ;
print "Content-type: text/html\n\n";
print $json_obj->pretty->encode(\%perl_data);
以下是所有内容都经过字符串化的输出:
Content-type: text/html
{
"numbers" : {
"nested" : [
"1",
"-2",
"4",
"2",
"5",
"6"
]
},
"mix" : {
"AnotherLevel" : [
"null",
"\"Temp\"",
"4",
"2",
"5",
"6"
]
}
}
在上面的代码中,我甚至尝试了以下方法,但没有效果
use JSON;
my $json_obj = JSON;
非常感谢您的帮助。不要将它们初始化为字符串,这样您就不会有问题:
use strict;
use warnings;
use CGI qw/param/;
use JSON::XS;
my $json_obj = JSON::XS->new->allow_nonref;
## Build some Perl data
my %perl_data = (
'numbers' => {'nested' => [1, -2, 4, 2, 5, 6]},
'mix' => {'AnotherLevel' => [qw/null "Temp"/, 4, 2, 5, 6]},
);
print "Content-type: text/html\n\n";
print $json_obj->pretty->encode(\%perl_data);
产出:
Content-type: text/html
{
"numbers" : {
"nested" : [
1,
-2,
4,
2,
5,
6
]
},
"mix" : {
"AnotherLevel" : [
"null",
"\"Temp\"",
4,
2,
5,
6
]
}
}
实际上,有一个很好的示例,它描述了如何将Perl数据结构序列化为JSON。特别是对于标量:
JSON::XS will encode undefined scalars as JSON null values, scalars that have last
been used in a string context before encoding as JSON strings, and anything else
as number values.
当您使用qw
定义数字数组时,您是在字符串上下文中使用它们。(qw
表示“引用单词”,通常用于在定义单词列表时保存一些键入。)
还要注意,JSON中的null
由Perl中的unde
值表示。当您说qw/null/
时,您只是在创建文本字符串'null'
所以你有两个选择
按如下方式定义阵列:
$perl_data{'numbers'}{'nested'} = [1, -2, 4, 2, 5, 6] ;
$perl_data{'mix'}{'AnotherLevel'} = [undef, "Temp", 4, 2, 5, 6] ;
或者,在序列化之前,通过向所有数字添加零来强制NUMIFI所有数字。例如
$perl_data{'numbers'}{'nested'} = [ map { $_ + 0 } qw/1 -2 4 2 5 6/ ];
这正是我需要的米勒先生。感谢闪电速度回复。感谢您的详细解释。