我见过的在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"]

最佳答案

如果运行该代码,则应收到以下错误:

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"]

09-04 19:18
查看更多