2

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);
1
  • can you post the dumper output, maybe we find a workaround. Commented Mar 25, 2015 at 7:35

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks it works, I've never used perl and trying to take over some code that was written by another developer. All the @$% signs in perl are new to me. I'm guessing @$ dereferences a pointer to an array?
@MehdiAbderezai: Perl was designed by a linguist so each identifier has a singular form $scalar (read this scalar), an unrelated plural form @array (read these array items) and a dictionary form %hash. It's built-in Hungarian notation. So to acccess one element (singular) of an array (plural) you write $array[0] etc. And yes, @$ dereferences an array reference, but it's best to read @$objects as the items in $object, just as @array is the items in array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.