首页 > 解决方案 > Perl 脚本 - 预期的 '"' 或 JSON 无效

问题描述

好的,我有这个方法:

sub config {
my $filename = 'perl_config.txt';
my $json_text = do {
    open(my $json_fh, "<:encoding(UTF-8)", $filename)
        or die("Can't open the file!");
    local $/;
    <$json_fh>
};
my $json = JSON->new;

my $data = $json->decode($json_text);

};

终端(翻译,而不是;))说:

'"' expected, at character offset 115 (before "}") at ./proj_perl.pl line 25

第 25 行表示开启my $data = $json->decode($json_text);

编辑:我已经编辑了我的问题并删除了不必要的代码。我仍然不知道出了什么问题。我的 JSON 文件是:

{
"local_host": "localhost",
"local_port": "6000",
"save_dir": "received_files",
"my_data": "my_data.txt",
}

标签: jsonperl

解决方案


这不是有效的 JSON:

{
"local_host": "localhost",
"local_port": "6000",
"save_dir": "received_files",
"my_data": "my_data.txt",
}

JSON 禁止使用最后的逗号。Javascript 允许它(我认为?),但 JSON 是基于 Javascript 的一个子集。

JSON::PP 和 JSON::XS(Perl JSON 模块支持的两个后端)都有一个放松模式,它们放松了一些 JSON 的语法限制,包括这个。

my $json = JSON->new->relaxed(1);

所以要么修复你的 JSON,要么使用宽松模式来解析它。


推荐阅读