proctree
proctree

Reputation: 85

", or } expected while parsing object/hash" error while parsing a JSON file

I'm trying to print the contents of the "name" field of a large .json file and I'm having problems with the parsing. So far I've tried open the .json file using "<:encoding(UTF-8)", but no luck so far.

This is my code, the error is on line 11:

#!/usr/bin/perl

use strict;
use warnings;
use JSON;

open(my $fh, "<:encoding(UTF-8)", "pokedex.json");
my $ejson = <$fh>;
close($fh);

my $djson = decode_json $ejson;
for(my $i=1;$i<=718;$i++){
    print $djson->{"$i"}{"name"}, "\n";
}

The error itself is , or } expected while parsing object/hash, at character offset 1 (before "\n") at jsonreverser.pl line 11.

I've ran the .json file through an online verifier, and it said it's correctly formatted. This is the link to the json file: http://vps.zazez.com/junk/pokedex.json

Upvotes: 5

Views: 3041

Answers (1)

mob
mob

Reputation: 118615

my $ejson = <$fh>;

is an assignment in scalar context, so you are only loading the first line of the input file into $ejson.

There are many ways to load an entire input stream into a scalar:

my $ejson = join '', <$fh>;

my $ejson = do {
    local $/;
    <$fh>;
};

Or use File::Slurp as asjo suggests.

Upvotes: 6

Related Questions