使用 bash 脚本合并 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29636331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merging JSON files using a bash script
提问by heena
I am very new to bash scripting. I attempted to write a script that merges several json files. For example:
我对 bash 脚本很陌生。我试图编写一个合并多个 json 文件的脚本。例如:
File 1:
文件 1:
{
"file1": {
"foo": "bar"
}
}
File 2:
文件2:
{
"file1": {
"lorem": "ipsum"
}
}
Merged File:
合并文件:
{
"file1": {
"foo": "bar"
},
"file2": {
"lorem": "ipsum"
}
}
This is what I came up with:
这就是我想出的:
awk 'BEGIN{print "{"} FNR > 1 && last_file == FILENAME {print line} FNR == 1 {line = ""} FNR==1 && FNR != NR {printf ","} FNR > 1 {line = jq -s '.[0] * .[1]' file1.json file2.json
} {last_file = FILENAME} END{print "}"}' json_files/* > json_files/all_merged.json
It works but I feel there is a better way of doing this. Any ideas?
它有效,但我觉得有更好的方法来做到这一点。有任何想法吗?
回答by Wintermute
Handling JSON with awk is not a terribly good idea. Arbitrary changes in meaningless whitespace will break your code. Instead, use jq
; it is made for this sort of thing. To combine two objects, use the *
operator, i.e., for two files:
用 awk 处理 JSON 并不是一个好主意。随意更改无意义的空格会破坏您的代码。相反,使用jq
; 它是为这种事情而做的。要组合两个对象,请使用*
运算符,即用于两个文件:
jq -s 'reduce .[] as $item ({}; . * $item)' json_files/*
And for arbitrarily many files, use reduce
to apply it sequentially to all:
对于任意多个文件,使用reduce
将其依次应用于所有文件:
The -s
switch makes jq
read the contents of the JSON files into a large array before handling them.
该-s
开关使jq
JSON 文件的内容在处理它们之前读取到一个大数组中。