如何在Perl中将简单数组编码为JSON?

时间:2014-03-20 00:58:46

标签: json perl

我在Perl中将对象编码为JSON字符串的所有示例都涉及哈希。如何将简单数组编码为JSON字符串?

use strict;
use warnings;
use JSON;
my @arr = ("this", "is", "my", "array");
my $json_str = encode_json(@arr);  # This doesn't work, produced "arrayref expected"

# $json_str should be ["this", "is", "my", "array"]

1 个答案:

答案 0 :(得分:23)

如果运行该代码,则会出现以下错误:

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)

您只需将参考传递给\@arr

即可
use strict;
use warnings;

use JSON;

my @arr = ("this", "is", "my", "array");
my $json_str = encode_json(\@arr);  # This will work now

print "$json_str";

输出

["this","is","my","array"]