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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8463919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:06:21  来源:igfitidea点击:

How to convert a simple hash to json in Perl?

jsonperlencodingutf-8hash

提问by Steve

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>

回答by Quentin

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.

添加缺少的样板。

#!/usr/bin/perl

use strict;
use warnings;

use JSON;

my $name = "test";
my $type = "A";
my $data = "1.1.1.1";
my $ttl  = 84600;

Make the hash a hash and not an array and don't forget to localise it: my %

使散列成为散列而不是数组,并且不要忘记对其进行本地化: my %

my %rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);

Actually use the encode_jsonmethod (passing it a hashref):

实际使用该encode_json方法(将其传递给 hashref):

my $json = encode_json \%rec_hash;

Output the result:

输出结果:

print $json;

And that works as I would expect without errors.

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

回答by Marius Kjeldahl

Try %rec_hash = ...instead. @indicates a list/array, while %indicates a hash.

试试吧%rec_hash = ...@表示列表/数组,而%表示散列。