我的字符串如下。
{
"id": "1304145"
,"Name" : "Ravi"
,"State" : "KAR"
,"Comp" : "CTL"
}
,{
"id": "2488398"
,"Name" : "Abhik"
,"State" : "TEL"
,"Comp" : "WFG"
}
,{
"id": "89039487"
,"Name" : "Jana"
,"State" : "ODS"
,"Comp" : "TOT"
}
我想提取{}中存在的每个子字符串,并按照以下格式制作格式
ID Name State Comp
1304145 Ravi KAR CTL
2488398 Abhik TEL WFG
89039487 Jana ODS TOT
我试过了,但我的脚本没有给出确切的输出。 需要你帮助解决这个问题。
答案 0 :(得分:2)
看起来很像JSON。
如果是:
#!/usr/bin/env perl
use strict;
use warnings 'all';
use JSON;
my $json = from_json(do{local $/;<DATA>});
my @header = qw ( id Name State Comp );
print join ( "\t", @header ), "\n";
foreach my $row ( @$json ) {
print join ( "\t",@{$row}{@header} ),"\n";
}
__DATA__
[{
"id": "1304145"
,"Name" : "Ravi"
,"State" : "KAR"
,"Comp" : "CTL"
},
{
"id": "2488398"
,"Name" : "Abhik"
,"State" : "TEL"
,"Comp" : "WFG"
}
,{
"id": "89039487"
,"Name" : "Jana"
,"State" : "ODS"
,"Comp" : "TOT"
}
]
给出:
id Name State Comp
1304145 Ravi KAR CTL
2488398 Abhik TEL WFG
89039487 Jana ODS TOT
假设您确实拥有JSON - 我必须在您的代码段周围添加[]
。如果它不是JSON
那么某人做了一些肮脏的事情,创造了一些看起来很像JSON的东西,但那并不是。
答案 1 :(得分:2)
如果出于某种原因,数据不是应该是JSON,并且键和值始终用双引号括起来,那么你可以解析很容易用正则表达式
use strict;
use warnings 'all';
my $s = <<END_STRING;
{
"id": "1304145"
,"Name" : "Ravi"
,"State" : "KAR"
,"Comp" : "CTL"
}
,{
"id": "2488398"
,"Name" : "Abhik"
,"State" : "TEL"
,"Comp" : "WFG"
}
,{
"id": "89039487"
,"Name" : "Jana"
,"State" : "ODS"
,"Comp" : "TOT"
}
END_STRING
my @data = map { { /"([^"]*)"/g } } $s =~ /\{[^{}]*\}/g;
my $fmt = "%-11s %-7s %-7s %s\n";
printf $fmt, qw/ ID Name State Comp /;
for my $item ( @data ) {
printf $fmt, @{$item}{qw/ id Name State Comp /};
}
ID Name State Comp
1304145 Ravi KAR CTL
2488398 Abhik TEL WFG
89039487 Jana ODS TOT