我有一个 perl 代码片段
use JSON::XS;
$a = {"john" => "123", "mary" => "456"};
print encode_json($a),"\n";
输出是
{"john":"123","mary":"456"}
想知道是否有一个选项可以使 encode_json 函数(来自 JSON::XS 模块)对其进行编码,以便值 (123, 456) 不被双引号括起来。即,喜欢
{"john":123,"mary":456}
不幸的是,我无法更改 $a 中的散列,因为它是从另一个函数传递给我的。不知道encode_json()有没有什么技巧。
谢谢!
最佳答案
在 JSON 序列化之前,您可能需要自己预处理数据。
此解决方案使用 Data::Leaf::Walker 遍历任意结构,将字符串转换为数字。
use JSON;
use Data::Leaf::Walker;
use Scalar::Util qw();
my $a = {"john" => "123",
"mary" => ["456","aa"],
"fred" => "bb",
"nested" => {"Q" => undef, "A" => 42},
};
my $walker = Data::Leaf::Walker->new( $a );
while (my ( $key_path, $value ) = $walker->each ) {
$walker->store($key_path, $value + 0)
if Scalar::Util::looks_like_number $value;
};
print to_json($a);
输出:{"john":123,"nested":{"A":42,"Q":null},"mary":[456,"aa"],"fred":"bb”
关于json - 编码不带引号的 json 数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24813285/