如何在Perl中将简单哈希转换为json?
我使用下面的代码来编码一个简单的散列如何在Perl中将简单哈希转换为json?,json,perl,encoding,utf-8,hash,Json,Perl,Encoding,Utf 8,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); 但我得到了以下错误: hash- or arrayref expected <not a simple scalar
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>
应为哈希或arrayref
试试%rec\u hash=…
@
表示一个列表/数组,而%
表示一个哈希。您的代码似乎缺少一些重要的块,因此让我们添加缺少的位(我在这里做一些假设)并在执行时进行修复
添加缺少的样板
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
my $name = "test";
my $type = "A";
my $data = "1.1.1.1";
my $ttl = 84600;
将哈希设置为哈希而不是数组,不要忘记对其进行本地化:my%
my %rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);
实际使用encode_json
方法(传递一个hashref):
输出结果:
print $json;
这是我所期望的,没有错误。非常感谢您为我指出这些错误。我正在学习Perl,我没有注意到我试图再次使用数组作为hash lol Thx+1!缺少反斜杠(
\%rec\u hash
)是我的问题
print $json;