如何在 Perl 中解码 JSON 如果值有 或多行

  • 本文关键字:如果 JSON Perl 解码 json perl
  • 更新时间 :
  • 英文 :


如果值包含多行,如何解码 JSON 文件

a.json 文件:

{
            "sv1" : {
                  "output" : "Hostname: abcd
                              asdkfasfjsl",
                  "exp_result" : "xyz"
              }
}

当我尝试读取上面的 json 文件时,我遇到错误"解析 JSON 字符串时遇到无效字符,字符偏移量为 50(在" ..."之前)"

读取上述 JSON 文件的代码:

 #!/volume/perl/bin/perl -w
 use strict;
 use warnings;
 use JSON;
 local $/;
 open(AA,"<a.json") or die "can't open json file : $!n";
 my $json = <AA>;
 my $data = decode_json($json);
 print "reading output $data->{'sv1'}->{'output'}n"; 
 print "reading output $data->{'sv1'}->{'exp_result'}n";
 close AA;

除了 JSON 是否有效(请参阅对问题的评论)之外,您只读取文件中的第一行。

my $json = <AA>;

这是一个标量变量,只接收一行。

使用数组获取所有行:

my @json = <AA>;
my $json = join "n", @json;

甚至更好:使用File::Slurp::read_file通过一个简单的命令获取文件的全部内容。

use File::Slurp qw/read_file/;
my $json = read_file( "a.json" );

最新更新