2012-03-08 18 views
0

私はこの形式をPerlでJSON形式に変換するには?

私の元の形式である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 ] 
] 

どのように?

おかげで、

+1

http://search.cpan.org/perldoc?JSON – TLP

答えて

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 
. 
関連する問題