Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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
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?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2014-09-20 20:26 GMT
Find Nodes?
    Voting Booth?

    How do you remember the number of days in each month?

    Results (161 votes), past polls