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?
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With