从Perl中的JSON-String解码哈希

问题描述:

为什么这不起作用?

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

我得到了错误:

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

所以我将其更改为:

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

但是显然%myHash$myHashDecoded不同.

如何从JSON字符串恢复适当的哈希?

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

假设您使用的是JSON.pm,则文档说:

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

encode_json的反义词:需要一个UTF-8(二进制)字符串,并尝试将其解析为UTF-8编码的JSON文本,并返回生成的引用.

因此,您要取回所放入的内容.您要插入一个hashref,而您又要返回一个hashref.

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

如果您想要常规散列,则只需像其他任何hashref一样取消引用它即可:

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;