繁体   English   中英

使用sed或perl解析JSON文件

[英]Parsing JSON file using sed or perl

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

  • field6 =固定字符串
  • value6 =固定字符串
  • value30 =变化的字符串
  [ {"field6" : "value6", "field30" : "value30" }, { "field6" : "value6", "field30" : "value30" } ] 

如果我理解正确,这个程序应该做你想要的:

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的价值iwth field6的。

这是你试图做的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM