V
V
V Federoff2016-03-27 12:10:23
Perl
V Federoff, 2016-03-27 12:10:23

How to parse JSON in Perl?

Hello everyone,
I have difficulty parsing data presented in JSON.

#!/usr/bin/perl
use diagnostics;
use JSON::XS;
use Data::Dumper;
my $json_data='{
  "href" : "http://localhost/profiles",
  "items" : [
    {
      "href" : "http://localhost/id111",
      "Child" : {
        "name" : "Jack",
        "age" : "11",
        "pet" : "Cat"
      }
    },
    {
      "href" : "http://localhost/id303",
      "Child" : {
        "name" : "David",
        "age" : "8",
        "pet" : "Dog"
      }
      },
      {
      "href" : "http://localhost/id516",
      "Child" : {
        "name" : "Merry",
        "age" : "10",
        "pet" : "Hamster"
      }
    }
  ]
}';

print Dumper(decode_json ($json_data));

Conclusion:
$VAR1 = {
          'href' => 'http://localhost/profiles',
          'items' => [
                       {
                         'href' => 'http://localhost/id111',
                         'Child' => {
                                      'pet' => 'Cat',
                                      'name' => 'Jack',
                                      'age' => '11'
                                    }
                       },
                       {
                         'href' => 'http://localhost/id303',
                         'Child' => {
                                      'age' => '8',
                                      'name' => 'David',
                                      'pet' => 'Dog'
                                    }
                       },
                       {
                         'href' => 'http://localhost/id516',
                         'Child' => {
                                      'name' => 'Merry',
                                      'pet' => 'Hamster',
                                      'age' => '10'
                                    }
                       }
                     ]
        };

I can't figure out what structures Perl translates JSON to.
How, for example, for each object "Child" to print out only the values ​​of its "name" and "pet"?
I'm waiting for your advice! Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pcdesign, 2016-03-27
@pcdesign

print Dumper( decode_json($json_data) );

my $ref = decode_json($json_data);
my $arr = $ref->{"items"};
for my $item ( @$arr ){

    print $item->{"Child"}->{"name"}, " ",  $item->{"Child"}->{"pet"};
    print "\n";

}

Result:
Jack Cat
David Dog
Merry Hamster

D
Denis Zagaevsky, 2016-03-27
@zagayevskiy

This thing is called an "associative array", in Perl it's called a hash.
Values ​​can be accessed via {}, for example VAR1{"items"}; will return you an array of items.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question