我使用以下代码来编码一个简单的散列

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.

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 %rec_hash = ('name'=>$name, 'type'=>$type,'data'=>$data,'ttl'=>$ttl);

实际使用encode_json方法(传递一个hashref):

my $json = encode_json \%rec_hash;

输出结果:

print $json;

这就像我预期的那样工作正常,没有任何错误.

Json相关问答推荐

我可以使用JQ来缩小数组中的json对象的范围吗?

在Reaction中从JSON文件中筛选数组

使用JQ在数组中 Select 第一个具有匹配项的项

如果主对象中已存在属性,则不应在Jolt中引用次对象

用巨大的值更新SQL Server中的nvarchar(max)

使用 JOLT 将日期格式转换为 JSON

带有 API 测试的 Typescript JSON 模式验证

为什么解析的字典相等而腌制的字典不相等?

如何使用 React 从 NASA IMAGES API 中解构所需信息

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

Servicestack 返回数组而不是带有数组的对象

hook到 Decodable.init() 以获得未指定的键?

JSON 模式验证

如何使用 Kotlin + Jackson 将 JSON 反序列化为 List

哪个更好:Json 或 XML (PHP)

使用 c# 通用地展平 Json

从 HttpResponse 获取 json

Django:TypeError:[] 不是 JSON 可序列化的为什么?

Newtonsoft 对象 → 获取 JSON 字符串

Javascript对象和JSON对象有什么区别