【发布时间】:2017-09-22 04:53:07
【问题描述】:
我正在尝试编写一个 perl 代码来解析多个 JSON 消息。如果 JSON 文件仅包含一条 json 消息,我编写的 perl 代码只会解析这些值。但是当该文件中有多条消息时它会失败。它抛出错误:“未定义的子例程 &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" : []
}
我解析单个 JSON 消息的 perl 代码:
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";
}
【问题讨论】:
-
错误消息意味着您可能错过了一个依赖项。您是否使用通过一堆操作系统软件包安装的系统 Perl?您的 JSON 没有多个结构。看起来它是一个缺少最外层花括号
{}的对象。你能修复输入吗? -
感谢您指出。我已经放了外部大括号。
-
你需要升级鲤鱼。试试
cpan Carp。 -
如果 JSON 文件 tmp1.json 包含以下单个消息,则我的代码有效:{ "tag1" : "", "tag2" : true, "tag3" : [ { "status" : " TRUE”,“姓名”:“DEF”,“年龄”:“28”,“性别”:“f”},{“状态”:“FALSE”,“姓名”:“PQR”,“年龄”:“ 39”,“性别”:“f”}],“tag4”:“失败”,“tag5”:“/test/test1/test2/test3/supertest2/test02”,“tag6”:“”}
-
请编辑您的问题以显示导致问题的真实数据,或产生相同错误的一些类似数据。