Hi there Monks
I have to extract some values from a JSON data. I have a sample here where I cant get to one of the values in one of the blocks.
I would like to have this as a result:
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.
But I can not get to the value:
Yes: Mary Lou - 11111 | 1
Instead, I am getting just this:
Yes: Mary Lou - 22222 | 2
Yes: John De - 33333 | 1
Yes: Smith Doe - 4444 | 1
No sec value, just the name: Joseph D.
Any help on that?
#!/usr/bin/perl
use strict;
use warnings;
use JSON::XS;
use JSON qw( );
use Data::Dumper;
my $json = '{
"required": [
{
"docs": [
{
"sec": "11111",
"number": "1"
}
],
"docs": [
{
"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_da
+ta->{'number'} \n";
}
}
}else {
warn "\n No sec value, just the name: $dta->{'name'} \n\n";
}
}
Thanks for looking!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.