in reply to Re^2: Processing JSON with Perl
in thread Processing JSON with Perl
You are quick
But what if the json is fluid, and $data->{sections}[3] is not always directions, but you want to do the directions? Just search for directions and keep its reference!
Result:use strict; use warnings; my $data = { 'sections' => [ { 'images' => [], 'level' => 1, 'content' => [], 'title' => '10-minute Turkey' }, { 'images' => [], 'level' => 2, 'content' => [ { 'text' => 'Makes 4 servings.', 'type' => 'paragraph' } ], 'title' => 'Description' }, { 'images' => [], 'level' => 2, 'content' => [ { 'elements' => [ { 'elements' => [], 'text' => 'abc' }, { 'elements' => [], 'text' => 'efg' }, { 'elements' => [], 'text' => 'hij' }, ], 'type' => 'list' } ], 'title' => 'Ingredients' }, { 'images' => [], 'level' => 2, 'content' => [ { 'elements' => [ { 'elements' => [], 'text' => 'tuv' }, { 'elements' => [], 'text' => 'wxy' }, { 'elements' => [], 'text' => 'z12' }, ], 'type' => 'list' } ], 'title' => 'Directions' } ] }; #deepdump($data,'$data->'); my $directions; for my $i (@{$data->{sections}}) { if ($i->{title} eq 'Directions') {$directions=$i} } if ($directions) { deepdump($directions,'$directions->'); } sub deepdump { my $data=shift; my $isname=shift; my $iam=ref $data; if ($iam eq 'HASH') { my @keys=keys(%$data); if (0==scalar(@keys)){print $isname.'={}'."\n";} else {for my $k (@keys) { deepdump($data->{$k},$isname.'{'.$k.'}'); +} } } # hash elsif ($iam eq 'ARRAY') { my $ict=0; if (0==scalar(@$data)){print $isname.'=[]'."\n";} else {for my $i (@$data) { deepdump($data->[$ict],$isname.'['.$ict.' +]'); $ict++} } } # array else {print $isname.'='.$data."\n";} } exit;
I think this second hint may also prove usefull!$directions->{title}=Directions $directions->{level}=2 $directions->{content}[0]{type}=list $directions->{content}[0]{elements}[0]{elements}=[] $directions->{content}[0]{elements}[0]{text}=tuv $directions->{content}[0]{elements}[1]{elements}=[] $directions->{content}[0]{elements}[1]{text}=wxy $directions->{content}[0]{elements}[2]{text}=z12 $directions->{content}[0]{elements}[2]{elements}=[] $directions->{images}=[]
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Processing JSON with Perl
by DanielSpaniel (Scribe) on Feb 20, 2017 at 11:03 UTC |