我在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"]
答案 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"]