0
我正在尝试编写一个perl代码来解析多个JSON消息。如果JSON文件只包含一个json消息,我写的perl代码只解析这些值。但是当该文件中有多条消息时它会失败。它会抛出错误:“未定义的子程序&鲤鱼:: shortmess_heavy”。 JSON文件是采用以下格式:解析多个JSON消息的Perl代码
{
"/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";
}
请帮助。
谢谢!
错误消息意味着你可能错过的依赖。您是否正在使用通过一堆操作系统软件包安装的系统Perl?你的JSON没有多个结构。它看起来像是缺少最外层大括号'{}'的对象。你能修复输入吗? – simbabque
感谢您指出。我已经把外括号。 – dash
您需要升级鲤鱼。尝试'cpan鲤鱼'。 – rustyx