in reply to Re: Processing JSON with Perl
in thread Processing JSON with Perl

Ah, yes. That looks very useful for me to understand it better. Thank you very much, I appreciate it. I'll have a play around over the next day or two, but I think I can figure it out given your post.

Thanks!

Replies are listed 'Best First'.
Re^3: Processing JSON with Perl
by huck (Prior) on Feb 17, 2017 at 21:09 UTC

    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!

    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;
    Result:
    $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}=[]
    I think this second hint may also prove usefull!

      Didn't realize you'd posted more - sorry for delay in replying! Thanks. Yeah, that's awesome stuff.

      I did get a chance to play with the original code you posted and got it working nicely with what I need to do, and I can learn something from that for sure. I'll look at the new bits you've posted too, as I'm sure that will come in handy.

      Thanks again!