如何在Perl中将简单数组编码为JSON? [英] How do I encode a simple array into JSON in Perl?

查看:345
本文介绍了如何在Perl中将简单数组编码为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

All the examples that I've seen of encoding objects to JSON strings in Perl have involved hashes. How do I encode a simple array to a JSON string?

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

推荐答案

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

If you run that code, you should get the following error:

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

您只需要将引用传递给您的\@arr

You simply need to pass a reference to your \@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"]

这篇关于如何在Perl中将简单数组编码为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆