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

编程入门 行业动态 更新时间:2024-10-26 14:34:58
本文介绍了如何在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?

本文发布于:2023-10-30 07:55:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   简单   如何在   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!