#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    75
    Rep Power
    11

    Looping though Array in a Hash that contains a hash


    I could use some help I have a json that im grabbing that I get thats a hash that contains and array and in that array is a hash. And im tying to loop though the array but having problems trying to get that part to work.
    I can print $json_hash2{'field'}[0]{'name'} and $json_hash2{'field'}[1]{'name'}
    but making a loop for that array filed 0 1 2 ect ... is where im having a issue. Any Help?

    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    use Data::Dumper;
    use JSON;
    
    my $hasin = "{\"field\":[{\"id\":1,\"name\":\"name1\"},{\"id\":2,\"name\":\"name2\"}]}";
    my %json_hash2 = %{ decode_json($hasin) };
    print Dumper(%json_hash2);
    print "Name:\t\t" . $json_hash2{'field'}[0]{'name'} . "\n";
    print "Name2:\t\t" . $json_hash2{'field'}[1]{'name'} . "\n";
    foreach my $j_arr (@{ $json_hash2{'field'}}) {
        #print "$j_arr{'name'}\n";
    }
    Code:
    $VAR1 = 'field';
    $VAR2 = [
              {
                'name' => 'name1',
                'id' => 1
              },
              {
                'name' => 'name2',
                'id' => 2
              }
            ];
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Location
    Paris area, France
    Posts
    843
    Rep Power
    496
    A quick test under the Perl debugger:

    Code:
      DB<1> $json_hash2{'field'}[0]{'name'} = 0;
    
      DB<2> $json_hash2{'field'}[1]{'name'} = 1;
    
      DB<3> use Data::Dumper;
    
      DB<4> print Dumper \%json_hash2;
    $VAR1 = {
              'field' => [
                           {
                             'name' => 0
                           },
                           {
                             'name' => 1
                           }
                         ]
            };
    
      DB<5> for $val (@{$json_hash2{field}}) { print "@$val{name}\n";}
    0
    1
    I hope this helps.

    Comments on this post

    • krisrmgua agrees : Thanks!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    10
    Rep Power
    0
    Change

    print "$j_arr{'name'}\n";

    to

    print "$j_arr->{'name'}\n"; (or $$j_arr{name})

    $j_arr might be better named $hashref (or $href).

    Comments on this post

    • krisrmgua agrees : those work thanks a ton!
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    75
    Rep Power
    11
    Thats it! "@$" in my print for my loop... Thanks a Ton!

IMN logo majestic logo threadwatch logo seochat tools logo