bsd
bsd

Reputation: 6173

How to extract json value in perl

i am trying to extract the the values which I need 'system1 system2 system3 system4' . I used to extract the content from $json output like below. I am getting error ARRAY(0x210e150). Please suggest how to retrieve those values only.

$VAR1 = {
          'response' => {
                          'mydocs' => [
                                      {
                                        'host' => 'system1'
                                      },
                                      {
                                        'host' => 'system2'
                                      },
                                      {
                                        'host' => 'system3'
                                      },
                                      {
                                        'host' => 'system4'
                                      }
                                      ],
                                      }

                                   };

use LWP::Simple;              
use JSON;    
use Data::Dumper;               


my $url = "https://localhost/content;

my $json = from_json(get($url));

print Dumper($json); # received above output

print "$json->{'response'}->{'docs'}";

for my $data (@$json) {
    my $result = ref $data->{response} ? $data->{response}->{docs} : $data->{response};
    print "Result is $result\n";
}

Upvotes: 1

Views: 5440

Answers (1)

stevieb
stevieb

Reputation: 9296

$json is a hash reference, not an array reference, so looping over @$json won't work. What you need to do is delve down to where the array of hashes starts, and loop over that:

for my $host (@{ $json->{response}{mydocs} }){
    print "host: $host->{host}\n";
}

...and this:

print "$json->{'response'}->{'mydocs'}";

...is printing out the memory address of the mydocs array reference. What I do above is loop over this array reference extracting each hash reference it contains one at a time, then work on that.

Upvotes: 7

Related Questions