http://www.perlmonks.org?node_id=1186107


in reply to Re^2: Convert string to hash
in thread Convert string to hash

Building on AppleFritter's answers:

You can combine the loop through your results with the hash-building using map, which transforms one list into another, while performing some action on each element. In this case the action would be to add the appropriate key and value to your hash. (And we can transform the first list into a hash because a hash is a list of pairs ...)

my %json_hash = however_you_got_it(); my %new_hash = map { $_->{'certname'} => $_ } values %{ $json_hash{'r +esults'} };
Here map takes each element of the list returned by values(), which is a hashref, extracts the value of its key 'certname', uses that as the key in the new hash, and uses the entire hashref as the value.

Also note that I dereferenced the hashref $json_hash{'results'} before using it, because it's not "stable" Perl code to call values() (or keys()) on a hashref. I imagine you got a warning like "values on reference is experimental at ...", no?

Hope this helps!


The way forward always starts with a minimal test.