Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a simple hash to json in Perl?

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> 
like image 626
Steve Avatar asked Dec 11 '11 12:12

Steve


People also ask

What does encode_ JSON do in Perl?

Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, binary string.

How to parse JSON in Perl?

If you need to parse a JSON-formatted string in Perl, you can use a Perl module called JSON . The JSON module contains JSON-specific decode/encode functions that convert a JSON string into a Perl data structure, and vice versa.

What is hash JSON?

A Hash is a sparse array that uses arbitrary strings/objects (depending on the implementation, this varies across programming languages) rather than plain integers as keys. In Javascript, any Object is technically a hash (also referred to as a Dictionary, Associative-Array, etc).

Is a JSON object a hash table?

The Theory of JSONStandard objects are either a single key and value, or else a collection of keys and values which are equivalent to a hash table in most languages (learn about hash tables in Lua).


1 Answers

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); 

Actually use the encode_json method (passing it a hashref):

my $json = encode_json \%rec_hash; 

Output the result:

print $json; 

And that works as I would expect without errors.

like image 198
Quentin Avatar answered Oct 13 '22 08:10

Quentin