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

Vij*_*ati 9 perl json

我在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"]
Run Code Online (Sandbox Code Playgroud)

Mil*_*ler 24

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

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)
Run Code Online (Sandbox Code Playgroud)

你只需要传递一个引用你的 \@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";
Run Code Online (Sandbox Code Playgroud)

输出

["this","is","my","array"]
Run Code Online (Sandbox Code Playgroud)