Mehdi
Mehdi

Reputation: 792

Perl Json Array

I have an array of json objects in json format and in a file. I'm trying to load the file into perl, cycle through each item of the array (each json object) ...

I've used the code bellow, but it seams that no matter what I do, perl is treating it not as an array of objects, rather as a big object. Any help would be greatly appreciated.

my $json_text = do {
   open(my $json_fh, "<:encoding(UTF-8)", $filename)
      or die("Can't open \$filename\": $!\n");
   local $/;
   <$json_fh>
};

@objects = JSON->new->utf8->decode($json_text);
print  Dumper(@objects);

Upvotes: 2

Views: 2213

Answers (1)

Borodin
Borodin

Reputation: 126772

It sounds like your file contains a single JSON array. In that case your call to decode will return a reference to a Perl array, so if you write

my $objects = JSON->new->utf8->decode($json_text)

you can access each object as $objects->[0], $objects->[1] etc. Or you can iterate over them with

for my $object ( @$objects ) {

    # Do stuff with $object
}

Upvotes: 3

Related Questions