用于多个JSON消息解析的Perl代码

时间:2017-04-25 09:06:09

标签: json perl parsing

我正在尝试编写一个perl代码来解析多个JSON消息。我写的perl代码只解析了JSON文件只包含一条json消息时的值。但是当该文件中有多条消息时它会失败。它抛出错误:" Undefined subroutine& Carp :: shortmess_heavy"。 JSON文件采用以下格式:

    {
    "/test/test1/test2/test3/supertest4" : [],
    "/test/test1/test2/test3/supertest2" : [
     {
     "tag1" : "",
     "tag2" : true,
     "tag3" : [
        {
           "status" : "TRUE",
           "name" : "DEF",
           "age" : "28",
           "sex" : "f"
        },
        {
           "status" : "FALSE",
           "name" : "PQR",
           "age" : "39",
           "sex" : "f"
        }
     ],
     "tag4" : "FAILED",
     "tag5" : "/test/test1/test2/test3/supertest2/test02",
     "tag6" : ""
   }
],
"/test/test1/test2/test3/supertest1" : [
{
     "tag1" : "",
     "tag2" : false,
     "tag3" : [
        {
           "status" : "TRUE",
           "name" : "ABC",
           "age" : "21",
           "sex" : "m"
        },
        {
           "status" : "FALSE",
           "name" : "XYZ",
           "age" : "34",
           "sex" : "f"
        }
     ],
     "tag4" : "PASSED",
     "tag5" : "/test/test1/test2/test3/supertest1/test01",
     "tag6" : ""
   }
   ],
 "/test/test1/test2/test3/supertest6" : []
}

我的perl代码用于解析单个JSON消息:

use strict;
use warnings;
use Data::Dumper;
use JSON;
use JSON qw( decode_json );

my $json_file = "tmp1.json";

my $json;
open (my $fh, '<', $json_file) or die "can not open file $json_file";
{ local $/; $json = <$fh>; }
close($fh);

my $decoded = decode_json($json);

print "TAG4 = " . $decoded->{'tag4'} . "\n";
print "TAg5 = " . $decoded->{'tag5'} . "\n";

my @tag3 = @{ $decoded->{'tag3'} };
foreach my $tg3 ( @tag3 ) {
print "Name = ". $tg3->{"name"} . "\n";
print "Status = ". $tg3->{"status"} . "\n";
print "Age = ". $tg3->{"age"} . "\n";

}

请帮忙。

谢谢!

1 个答案:

答案 0 :(得分:3)

要解析多个JSON对象,请使用JSON :: XS的增量解析。

my $json = '{"foo":"bar"}   ["baz"]   true';

my @results = JSON::XS->new->incr_parse($json);
use Data::Dumper;
print Dumper \@results;

输出:

$VAR1 = [
          {
            'foo' => 'bar'
          },
          [
            'baz'
          ],
          bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' )
        ];