如何在Perl中将简单哈希转换为json?

时间:2011-12-11 12:25:19

标签: 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 allow_nonref to allow this>

2 个答案:

答案 0 :(得分:56)

您的代码似乎缺少一些重要的块,所以让我们添加缺少的部分(我将在这里做一些假设)并在我们去的时候解决问题。

添加缺失的样板。

#!/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):

my $json = encode_json \%rec_hash;

输出结果:

print $json;

这就像我期望的那样没有错误。

答案 1 :(得分:4)

请尝试使用%rec_hash = ...@表示列表/数组,而%表示哈希值。

相关问题