skip to Main Content

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


  1. 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:

    use warnings;
    use strict;
    use JSON;
    use Data::Dumper qw(Dumper);
    
    # open the json file
    my $json_file = 'example_json.json';
    
    open(my $fh, '<', $json_file) or die "Could not open file '$json_file' $!";
    my $string = do { local($/); <$fh> };
    close $fh;
    
    # decode the json file  
    my $json_data = decode_json($string);
    
    print Dumper($json_data);
    print "ID: $json_data->{glossary}{GlossDiv}{GlossList}{GlossEntry}{ID}n";
    

    Look at the data structure that Dumper outputs. Your foreach loop won’t work on it.

    Login or Signup to reply.
  2. <$fh> grabs just one line…your file appears to contain many lines so you probably want to be calling it like

    my $json_data = decode_json(join("",<$fh>));
    

    which will merge all the lines into one string and then pass it to the function to decode it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search