[英]Parsing JSON file using sed or perl
我有一個需要解析的json文件。 使用像sed / awk或perl這樣的腳本,如何提取value30並將其替換為以字符串“XX”為前綴的value6(例如,XX + 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.