Calbrenar
Calbrenar

Reputation: 31

looping through json in perl

I'm trying to grab some information out of a json export from Ping. My rusty Perl skills are failing me as I'm getting lost in the weeds with the dereferencing. Rather than bang my head against the wall some more I thought I'd post a question since all the google searches are leading here.

My understanding is that decode_json converts items into an array of hashes and each hash has strings and some other arrays of hashes as contents. This seems to bear out when attempting to get to an individual string value but only if I manually specify a specific array element. I can't figure out how to loop through the items.

The JSON comes back like this:

{
  "items":[
     {
       #lots of values here are some examples
       "type": "SP",
       "contactInfo": {
          "company": "Acme",
          "email": "[email protected]"
     }
 ]
}

I had no problems getting to actual values

#!/usr/bin/perl
use JSON;
use Data::Dumper;
use strict;
use warnings;
use LWP::Simple;


my $json;
{
  local $/; #Enable 'slurp' mode
  open my $fh, "<", "idp.json";
  $json = <$fh>;
  close $fh;
}

my $data = decode_json($json);

#array print $data->{'items'};
#hash print $data->{'items'}->[0];
#print $data->{'items'}->[0]->{'type'};

But, I can't figure out how to iterate through the array of items. I've tried for and foreach and various combinations of dereferencing, and it keeps telling me that the value I'm looping thru is still an array. If $data->{'items'} is an array, then presumably I should be able to do some variation of

foreach my $item ($data->{'items'})  

or

my @items = $data->{'items'};

for (@items)
{
  # stuff
}

But, I keep getting arrays back and I have to add in the ->[0] to get to a specific value.

Upvotes: 2

Views: 286

Answers (1)

toolic
toolic

Reputation: 62037

$data->{'items'} is a reference to an array (of hash references). You need to dereference it, with @{ }:

use JSON;
use strict;
use warnings;

my $json;
{
  local $/; #Enable 'slurp' mode
  $json = <DATA>;
}

my $data = decode_json($json);
for my $item (@{ $data->{items} }) {
    print "$item->{type}\n";
}

__DATA__
{
  "items":[
     {
       "type": "SP",
       "contactInfo": {
          "company": "Acme",
          "email": "[email protected]"
        }
     }
 ]
}

Output:

SP

Upvotes: 4

Related Questions