如何将此格式转换为perl中的JSON格式?
问题描述:
我想我的原始格式转换成JSON格式如何将此格式转换为perl中的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 ]
]
如何开发这样的脚本?
感谢,
答
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
.
http://search.cpan.org/perldoc?JSON – TLP 2012-03-08 04:51:50