Stephane
Stephane

Reputation: 5078

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>

Upvotes: 35

Views: 70292

Answers (2)

Quentin
Quentin

Reputation: 943537

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.

Upvotes: 72

Marius Kjeldahl
Marius Kjeldahl

Reputation: 6824

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

Upvotes: 4

Related Questions