3

I need to loop through several jsons and print out index 1 of each...

I start with a generated string containing my JSON data. I then decode the string and dump it to show exactly what I'm working with:

my $decoded = decode_json $string
print Dumper $string

This results in the following output:

$VAR1 = [
      {
        'hdr' => [
                   1,
                   'acknowledged',
                   '',
                   '/home/clanier/dev/test/sds-test/data/JPLIDR2015169.64575',
                   '2015/271-19:10:39.0101355',
                   '2015/271-19:10:39.2599252',
                   ''
                 ]
      },
      {
        'hdr' => [
                   2,
                   'acknowledged',
                   '',
                   '/home/clanier/dev/test/sds-test/data/JPLIDR2015169.64575',
                   '2015/271-19:10:39.3928414',
                   '2015/271-19:10:39.6397269',
                   ''
                 ]
      },
      {
        'hdr' => [
                   3,
                   'acknowledged',
                   '',
                   '/home/clanier/dev/test/sds-test/data/JPLIDR2015169.64575',
                   '2015/271-19:10:39.7726375',
                   '2015/271-19:10:40.0162758',
                   ''
                 ]
      }
    ];

Now I try to loop through this and print the word acknowledged for each one:

foreach my $hdr ( $decoded->{hdr} ) {
  print $hdr->[1];
}

I looked to this solution for help, but it appears I cannot even get as far as the original poster, due to "Not a HASH reference" errors. I was able to print a specific one previously, but I need to loop through and print all of them. This was the code for that: print $$decoded[0]->{'hdr'}->[1];

Community
  • 1
  • 1
codenaugh
  • 857
  • 2
  • 12
  • 27

1 Answers1

12

$decoded is an array reference, not a hash reference. You can't dereference it as a hash: ->{.

You can dereference it as an array, though:

for my $hdr (@$decoded) {
    print $hdr->{hdr}[1];
}

See perlreftut for more information about references in Perl.

choroba
  • 231,213
  • 25
  • 204
  • 289