perl $json_data = decode_json(< $fh>);

fdbelqdn  于 2023-05-23  发布在  Perl
关注(0)|答案(1)|浏览(139)

我试图运行一个简单的Perl JSON示例与JSON Perl模块,并不能找到行的问题:

my $json_data = decode_json(<$fh>);

我得到以下错误。任何帮助将不胜感激。

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
7fyelxc5

7fyelxc51#

decode_json函数的输入必须是一个字符串,但您正在尝试向其传递其他内容。
因为你已经打开了这个文件,你可以把它转换成一个字符串,然后把它传递给函数:

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";

查看Dumper输出的数据结构。你的foreach循环不会在上面工作。

相关问题