我想将原始格式转换为JSON格式
我原来的格式是:
RECORD
F recordType 18
F routingArea 04
F cellIdentifier 9E55
.
RECORD
F recordType 18
F routingArea 04
.
像这样转换:
[ #openfile
{ #convert RECORD to [
"recordType" : "18", #cut prefix F and convert to json
"routingArea" : "04",
"cellIdentifier" : "9E55" #no comma before },
},
{
"recordType" : "18",
"routingArea" : "04"
} #no comma before ]
]
如何开发这样的脚本?
谢谢,
答案 0 :(得分:2)
use warnings;
use strict;
use JSON;
my @ar;
my $inner_hash = {};
while (<DATA>) {
chomp;
if ($_ eq '.') {
push @ar, $inner_hash;
$inner_hash = {};
} elsif (/^F\s+(.*?)\s+(.*?)$/) {
$inner_hash->{$1} = $2;
}
}
my $json = to_json(\@ar);
print $json, "\n";
__DATA__
RECORD
F recordType 18
F routingArea 04
F cellIdentifier 9E55
.
RECORD
F recordType 18
F routingArea 04
.