jsonperlhashhash-of-hashes

Accessing values of json structure in perl


I have a json structure that I'm decoding that looks like this:

  person => {
    city => "Chicago",
    id => 123,
    name => "Joe Smith",
    pets => {
      cats => [
                { age => 6, name => "cat1", type => "siamese", weight => "10 kilos" },
                { age => 10, name => "cat2", type => "siamese", weight => "13 kilos" },
              ],
      dogs => [
                { age => 7, name => "dog1", type => "siamese", weight => "20 kilos" },
                { age => 5, name => "dog2", type => "siamese", weight => "15 kilos" },
              ],
    },
  },
}

I'm able to print the city, id, name by doing:

foreach my $listing ($decoded->{person})
{ 
    my $city = $listing->{city};
    my $name = $listing->{name};
    name - $city - \n";
}

however, I'm unsure of how to print the pets->cats or pets->dogs. I'm able to do a dump of them by:

my @pets = $listing->{pets}->{cats};
dump @pets;

but I'm not sure how to access them through the hash structure.


Solution

  • Assuming your $listing is a person you have to dereference array and hash refs.

    # as long as we are assuming $listing is a person
    # this goes inside the foreach you posted in your
    # question.
    
    # this will print all cats' names
    foreach my $cat ( @{ $listing->{pets}->{cats} } )
    {
        # here $cat is a hash reference
    
        say $cat->{name}; # cat's name
    }
    

    and so on for other stuff.

    To access them from the structure you can do:

    say $listing->{pets}->{cats}->[0]->{name}; # this will print 'cat1'