Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: JSON Structure Question

by hdb (Prior)
on May 23, 2013 at 14:07 UTC ( #1034959=note: print w/ replies, xml ) Need Help??


in reply to JSON Structure Question

The following code prints all the "leaves" of a complex data structure but you can add selection criteria operating on the keys as required.

use strict; use warnings; use JSON; my %dispatch = ('' => sub { print "$_[0]\n"; }, 'HASH' => sub { for my $key (keys %{$_[0]}) { search_and_replace_in_hash( $_[0]->{$key} +); } }, 'ARRAY' => sub { search_and_replace_in_hash( $_ ) for @{$_[0]}; + }, 'default' => sub { my ( $element, $op ) = @_; print STDERR ref($element).": unknown type of +reference\n" }, ); sub search_and_replace_in_hash { &{ $dispatch{ ref($_[0]) } // $dispatch{'default'} }(@_); } my $data = <<EOD; { "1": {"subject1": "value", "subject2": [{"subject3": "value", "subject +4": "value"}], "subject5": "value", "subject6": "value", "subject7": +"value"}, "2": {"subject1": "value", "subject2": [{"subject3": "value", "subject +4": "value"}], "subject5": "value", "subject6": "value", "subject7": +"value"}, "3": {"subject1": "value", "subject2": [{"subject3": "value", "subject +4": "value"}], "subject5": "value", "subject6": "value", "subject7": +"value"} } EOD $data = JSON->new()->decode( $data ); search_and_replace_in_hash( $data );


Comment on Re: JSON Structure Question
Download Code
Replies are listed 'Best First'.
Re^2: JSON Structure Question
by omegaweaponZ (Beadle) on May 23, 2013 at 16:00 UTC
    The closest way of explaining what I need is that I need to store not just what is in each hash key of 1{}. 2{}, but I physically need to store the top most level of each hash key. The json format cannot be modified in any way.

    I can use $data->{1}->{stuff} to get the value of stuff, and so on. So what am I missing to simply read through and loop line by line and get $data->{??????}. I would like to stick with the JSON package to learn the format structure better before exploring other packages.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (10)
As of 2015-07-08 06:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (94 votes), past polls