Decoding Hash from JSON-String in Perl
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;
On the following line, you do two things: you create a reference to the hash (\
), and you encode the result (encode_json
):
my $myHashEncoded = encode_json(\%myHash);
One the following line, you decode the JSON (decode_json
), but you don't "undo" the reference.
my %myHashDecoded = decode_json($myHashEncoded);
The real inverse operation would involve a hash derereference.
my %myHashDecoded = %{ decode_json($myHashEncoded) };
But that needlessly makes a (shallow) copy of the hash. Maybe you should just work with the reference instead.
my $myHashDecoded = decode_json($myHashEncoded);
By the way, the reason a reference is used is that it's impossible to pass a hash to a sub or to return a hash from a sub. Only list of scalar can be passed and returned.