Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding Hash from JSON-String in Perl

Tags:

json

hash

perl

Why does this not work?

my $myHashEncoded = encode_json \%myHash;
my %myHashDecoded = decode_json($myHashEncoded);

I get the error:

Reference found where even-sized list expected at ...

So I changed it to:

my $myHashEncoded = encode_json \%myHash;
my $myHashDecoded = decode_json($enableInputEncoded);

But then obviously %myHash is not the same as $myHashDecoded.

How do I restore a proper hash from the JSON string?

like image 460
Linus Avatar asked Jun 10 '15 14:06

Linus


2 Answers

Assuming you are using JSON.pm, the documentation says:

The opposite of encode_json: expects an UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference.

So you are getting back what you put in. You're putting in a hashref and you're getting a hashref back.

If you want a regular hash, then you just dereference it as you would any other hashref:

my $myHashRefDecoded = decode_json($myHashEncoded);
my %myHashDecoded = %$myHashRefDecoded;
like image 52
Quentin Avatar answered Sep 27 '22 15:09

Quentin


You are encoding a reference to a hash (encode_json \%myHash), which is correct. So when you decode your JSON string you are receiving a reference to a hash. Prepend a % sigil to a hash reference to dereference it.

$myHashReferenceDecoded = decode_json($myHashReferenceEncoded);
%myHashDecoded = %$myHashReferenceDecoded;
like image 42
mob Avatar answered Sep 27 '22 17:09

mob