{
"ticket": {
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}
}
,
"edition": "third",
"author": "Herbert Schildt"
}
这是我的JSON文件。我想从文件起始部分{"ticket":
和结束部分,"edition": "third", "author": "Herbert Schildt" }
。
最后输出我想这样:
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}
}
注意
不要仅使用JSON Perl来使用正则表达式。
更新
#!/usr/bin/perl
use JSON;
use Data::Dumper;
use Getopt::Long;
my($infile);
GetOptions('inFile=s' => \$infile);
my $json;
{
local $/;
open my $fh, "<", "$infile";
$json = <$fh>;
close $fh;
}
my $text = decode_json($json);
我已经完成了解码,但是如何删除起始和结束部分?
答案 0 :(得分:5)
假设您的JSON文件中的语法错误是偶然的,并使用逗号和数组结构修复它,这可行:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my $json = do {
local $/;
<DATA>;
};
my $data = decode_json($json);
my $data2 = $data->{ticket};
my $json2 = encode_json($data2);
print $json2, "\n";
__DATA__
{
"ticket": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
],
"edition": "third",
"author": "Herbert Schildt"
}
打印出来:
[{"language":"Java","edition":"third","author":"Herbert Schildt","id":"01"},{"language":"C++","edition":"second","author":"E.Balagurusamy","id":"07"}]