本文介绍了如何在Perl中将简单的哈希转换为json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码来编码一个简单的哈希
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);但是我收到以下错误:
hash- or arrayref expected <not a simple scalar, use allow_nonref to allow this>推荐答案
你的代码似乎缺少一些重要的块,所以让我们添加一些丢失的位(我会在这里做一些假设),并在我们走的时候修复一些事情。
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.
添加缺少的样板。
#!/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 %rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);实际使用 encode_json 方法(传递它一个hashref):
Actually use the encode_json method (passing it a hashref):
my $json = encode_json \%rec_hash;输出结果:
print $json;这样可以预期没有错误。
And that works as I would expect without errors.
更多推荐
如何在Perl中将简单的哈希转换为json?
发布评论