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


in reply to Re^2: How to use a json string with nested array and nested hash elements?
in thread How to use a json string with nested array and nested hash elements?

Well, as aitap mentioned above, @jsonarray = $decoded_json->{strarray} is wrong; it should be $jsonarray = $decoded_json->{strarray}. (It makes no sense to call ref() on an array either.)

Anyway, since $strarray is an array reference, you access its elements with $strarray->[$index], and if you need the whole array (in the foreach), you need to write @$strarray. (With hashes, the equivalents are $somevar->{$key} and %$somevar, respectively.)

Your structure is... well, let's tackle the strarray. It is an array of a single element, and that element contains a hash. And that is where you went wrong. I think you missed the arrays altogether. There's one under pick_location and the other one was under strarray. But let's try this in code:

# let's use an intermediate variable. # it's a good idea when dealing with complex data structures my $strarray = $decoded_json->{strarray}; # enumerate over the first array. for my $str (@$strarray) { # now you have a hash with refill_report # and inventory_report in $str # let's access the pick_location inside the refill_report hash my $refill = $str->{refill_report}; my $pick_aref = $refill->{pick_location}; for my $pick (@$pick_aref) { # now we have one hashref in $pick print $pick->{pickid}, "\n"; } # let's try sorting # $a is an element of @$pick_aref; so it is a hashref my @sorted = sort { $a->{inv} <=> $b->{inv} } @$pick_aref; print Dumper($_) for @sorted; }

It's not a bad idea to postfix your intermediate variables with _href or _aref (like I did for one variable) just to remember whether you are dealing with a hash reference or an array reference.

I hope this helps. I spent quite a while pondering on how to access a complex data structure that a module spat out for me, but that was quite a while ago.