Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

perl

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

like image 999
proctree Avatar asked Jul 25 '14 15:07

proctree


1 Answers

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.

like image 194
mob Avatar answered Sep 29 '22 20:09

mob