如何在 Perl 中将简单的哈希转换为 json?
我使用以下代码对简单的哈希进行编码,
use JSON;
my $name = "test";
my $type = "A";
my $data = "1.1.1.1";
my $ttl = 84600;
@rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);
但出现以下错误:
hash- or arrayref expected <not a simple scalar, use allow_nonref to allow this>
I'm using the following code to encode a simple hash
use JSON;
my $name = "test";
my $type = "A";
my $data = "1.1.1.1";
my $ttl = 84600;
@rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);
but I get the following error:
hash- or arrayref expected <not a simple scalar, use allow_nonref to allow this>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码似乎缺少一些重要的块,因此让我们添加缺少的位(我将在这里做出一些假设)并修复问题。
添加缺少的样板。
将散列设置为散列而不是数组,并且不要忘记对其进行本地化:
my %
实际上使用
encode_json
方法(向其传递 hashref):输出结果:
这正如我所期望的那样,没有错误。
Your code seems to be missing some significant chunks, so let's add in the missing bits (I'll make some assumptions here) and fix things as we go.
Add missing boilerplate.
Make the hash a hash and not an array and don't forget to localise it:
my %
Actually use the
encode_json
method (passing it a hashref):Output the result:
And that works as I would expect without errors.
尝试使用
%rec_hash = ...
代替。@
表示列表/数组,而%
表示哈希。Try
%rec_hash = ...
instead.@
indicates a list/array, while%
indicates a hash.