Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Parsing nested JSON

by AnomalousMonk (Bishop)
on Oct 05, 2021 at 00:28 UTC ( #11137220=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11137220]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2022-01-18 15:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (53 votes). Check out past polls.

    Notices?