blue panther
blue panther

Reputation: 253

Loop through JSON Structure in Perl

How to fill list with JSON data?

Here's my code:

my $groups = get_groups($t);
my @group;
my $i = 0;
do {
    push(@group, {
        groups  => [
            { type => $groups->{groups}->[$i]->{type} , group => $groups->{groups}->[$i]->{group} },
        ]
    });
    $i++;
} while ($i < length $groups->{groups});

Here is the json sample:

{
    "error":false,
    "message":"success",
    "group":[
        {"type":1,"group":"group1"},
        {"type":2,"group":"group2"},
        {"type":3,"group":"group3"},
        {"type":4,"group":"group4"},
        {"type":5,"group":"group5"}
    ]
}

Function get_groups($t); will return above json. I want to get the array group and put it into list groups. But I got:

Can't use string ("0") as a HASH ref while "strict refs" in use

Upvotes: 0

Views: 241

Answers (1)

simbabque
simbabque

Reputation: 54381

From the documentation of length:

Returns the length in characters of the value of EXPR. If EXPR is omitted, returns the length of $_ . If EXPR is undefined, returns undef.

This function cannot be used on an entire array or hash to find out how many elements these have. For that, use scalar @array and scalar keys %hash , respectively.

To get the number of elements in an array reference, you need to dereference it and put it into scalar context.

my $foo = [ qw/a b c/ ];
my $number_of_elements = scalar @{ $foo }; # 3

What you actually want to do is loop over every team in the teams array. No need to get the number of elements.

my @teams;
foreach my $team ( @{ $opsteams->{teams} } ) {
    push @teams, {
        type => $team->{type},
        team => $team->{team},
    };
}

There are some extra layers of depth in your code. I'm not sure what they are for. It actually looks like you just want the teams in @teams, which really would be

my @teams = @{ $opsteams->{teams} };

Upvotes: 2

Related Questions