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