2014-01-19 112 views
1

我有一个需要解析的json文件。 使用像sed/awk或perl这样的脚本,如何提取value30并将其替换为以字符串“XX”为前缀的value6(例如.XX + value30)。 其中:使用sed或perl解析JSON文件

  • 字段6 =固定字符串
  • value6 =固定字符串
  • 值30 =不同的字符串
[ 
    {"field6" : "value6", "field30" : "value30" }, 
    { "field6" : "value6", "field30" : "value30" } 
] 
+3

三个字;不不不。 – tripleee

+3

那么,有了适当的JSON库,Perl应该没问题,实际上。 – tripleee

+3

不要手动做。使用像[Perl JSON]这样的模块(http://search.cpan.org/~makamaka/JSON-2.90/lib/JSON.pm#decode_json) – grebneke

回答

3

如果我理解正确的话,这个程序应该做的你在做什么:

use JSON qw(decode_json encode_json); 
use strict; 
use warnings; 

# set the input line separator to undefined so the next read (<>) reads the entire file 
undef $/; 
# read the entire input (stdin or a file passed on the command line) and parse it as JSON 
my $data = decode_json(<>); 

my $from_field = "field6"; 
my $to_field = "field30"; 

for (@$data) { 
    $_->{$to_field} = $_->{$from_field}; 
} 

print encode_json($data), "\n"; 

它依靠的JSON模块上安装,您可以通过cpanm安装(这应该是最现代的Perl发行版中提供):

cpanm install JSON 

如果程序文件substitute.pl和你的JSON中阵列是data.json,那么您可以运行它:

perl substitute.pl data.json 
# or 
cat data.json | perl substitute.pl 

应该产生:

[{"field30":"value6","field6":"value6"},{"field30":"value6","field6":"value6"}] 

替换field30的值为field6's。

这是你正在尝试做什么?

+1

fyi'encode_json'和'decode_json'优于'to_'和'from_',因为它们正确处理utf8。 –

+3

另外cpan plus已经不在时尚之列(并且在最新的Perl版本中脱离核心)。核心'cpan'客户端将会很好,现在通常首选'cpanm'(cpanminus)。 https://metacpan.org/pod/cpanm –

+0

非常感谢您提供有用的见解,最佳实践以及Kyle的示例代码。我会把它们拼凑起来。 – DPC