我正在尝试编码perl嵌套哈希并将其发送到某个Web应用程序。 不知何故,json编码器将数字或浮点数转换为字符串。 Web应用程序将数据视为字符串,无法绘制图表。我可以在Web应用程序中添加代码以将它们转换回数字,但我正在寻找更好的解决方案,首先不要将数字作为字符串。
以下是代码:
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;
非常感谢任何帮助。
答案 0 :(得分:1)
不要将它们初始化为字符串,并且不会出现问题:
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
]
}
}
答案 1 :(得分:1)
JSON::XS documentation实际上有一个很好的section,它描述了如何将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中的undef
值表示。当您说qw/null/
时,您只需创建文字字符串'null'
。
所以你有两个选择。
像这样定义你的数组:
$perl_data{'numbers'}{'nested'} = [1, -2, 4, 2, 5, 6] ;
$perl_data{'mix'}{'AnotherLevel'} = [undef, "Temp", 4, 2, 5, 6] ;
或者,在序列化之前,通过向它们添加零来强制数字化所有数字。 E.g。
$perl_data{'numbers'}{'nested'} = [ map { $_ + 0 } qw/1 -2 4 2 5 6/ ];