I am trying to run a simple Perl JSON example with the JSON
Perl module
and can’t find the issues with line:
my $json_data = decode_json(<$fh>);
I get the following error. Any help would be appreciated.
Susan@Kona MINGW64 /c/data/data/data/quickPerlTest
$ perl test.pl
, or } expected while parsing object/hash, at character offset 3 (before "(end of string)") at test.pl line 9.
use JSON;
# open the json file
my $json_file = 'example_json.json';
open(my $fh, '<', $json_file) or die "Could not open file '$json_file' $!";
# decode the json file
my $json_data = decode_json(<$fh>);
# access the elements of the json file
foreach my $item ( @{$json_data->{items}} ) {
print "ID: $item->{id}n";
print "Title: $item->{title}n";
}
Susan@Kona MINGW64 /c/data/data/data/quickPerlTest
$ cat example_json.json
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language.",
"GlossSeeAlso": [ "GML", "XML" ]
},
"GlossSee": "markup"
}
}
}
}
}
Susan@Kona MINGW64 /c/data/data/data/quickPerlTest
$ perl --version | grep version
This is perl 5, version 36, subversion 0 (v5.36.0) built for x86_64-msys-thread-multi
2
Answers
The input to the decode_json function must be a string, but you are trying to pass something else to it.
Since you already opened the file, you can slurp it into a string, then pass that to the function:
Look at the data structure that
Dumper
outputs. Yourforeach
loop won’t work on it.<$fh>
grabs just one line…your file appears to contain many lines so you probably want to be calling it likewhich will merge all the lines into one string and then pass it to the function to decode it