http://qs321.pair.com?node_id=11137220


in reply to Parsing nested JSON

my $json = '{ "required": [ { "docs": [ { "sec": "11111", "number": "1" } ], "docs": [ { "sec": "22222", "number": "2" } ], "name": "Mary Lou" }, ... }';

It seems strange that the value of "docs" in the quoted code should be an array with a single hash element. Was the original intention to make this an array of hashes? The posted code for printing the decoded JSON suggests this. Making this change to the JSON string produces the desired output with the posted code:

Win8 Strawberry 5.8.9.5 (32) Mon 10/04/2021 20:14:50 C:\@Work\Perl\monks >perl use strict; use warnings; use JSON; use Data::Dumper; my $json = '{ "required": [ { "docs": [ { "sec": "11111", "number": "1" }, { "sec": "22222", "number": "2" } ], "name": "Mary Lou" }, { "docs": [ { "sec": "33333", "number": "1" } ], "name": "John De" }, { "docs": [ { "sec": "4444", "number": "1" } ], "name": "Smith Doe" }, { "name": "Joseph D." } ] }'; my $json_data = JSON->new; my $data = $json_data->decode($json); for my $dta ( @{ $data->{ required } || [] }) { if (scalar @{ $dta->{ docs } || [] } ) { for my $doc_data (@{ $dta->{ docs } || [] }) { if ($doc_data->{'sec'}) { print "\n Yes: $dta->{'name'} - $doc_data->{'sec'} ", "| $doc_data->{'number'} \n"; } } } else { warn "\n No sec value, just the name: $dta->{'name'} \n\n"; } } ^Z Yes: Mary Lou - 11111 | 1 Yes: Mary Lou - 22222 | 2 Yes: John De - 33333 | 1 Yes: Smith Doe - 4444 | 1 No sec value, just the name: Joseph D.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: Parsing nested JSON
by BillKSmith (Monsignor) on Oct 05, 2021 at 17:09 UTC
    I suspect that AnomalousMonk has given the correct answer to your previous post (Looping through an array) as well. Because there was nothing obviously wrong with that data (except for the translation from JSON to perl) , we assumed that your problem was with the code.
    Bill