通过 perl 解析以 JSON 编码的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3695105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing an array encoded in JSON through perl
提问by Niraj Nawanit
I am using the Following Perl code to parse an array in JSON, using the JSONmodule. But the array returned has length 1 and I am not able to iterate over it properly. So the problem is I am not able to use the array returned.
我正在使用以下 Perl 代码来解析 JSON 中的数组,使用JSON模块. 但是返回的数组长度为 1,我无法正确迭代它。所以问题是我无法使用返回的数组。
#!/usr/bin/perl
use strict;
my $json_text = '[ {"name" : "abc", "text" : "text1"}, {"name" : "xyz", "text" : "text2"} ]';
use JSON;
use Data::Dumper::Names;
my @decoded_json = decode_json($json_text);
print Dumper(@decoded_json), length(@decoded_json), "\n";
The output comes :
输出来了:
$VAR1 = [
{
'text' => 'text1',
'name' => 'abc'
},
{
'text' => 'text2',
'name' => 'xyz'
}
];
1
回答by Chas. Owens
The decode_jsonfunctionreturns an arrayref, not a list. You must dereference it to get the list:
该decode_json函数返回一个数组引用,而不是一个列表。您必须取消引用它才能获得列表:
my @decoded_json = @{decode_json($json_text)};
You may want to read perldoc perlreftutand perldoc perlref
回答by Tobi Oetiker
Regarding JSON, you may want to make sure you install the JSON::XSmoduleas it is faster and more stable than the pure Perl implementation included with the JSONmodule. The JSONmodule will use JSON::XSautomatically when it is available.
关于 JSON,您可能需要确保安装该JSON::XS模块,因为它比JSON模块中包含的纯 Perl 实现更快、更稳定。该JSON模块将JSON::XS在可用时自动使用。

