使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:47:54  来源:igfitidea点击:

Merging JSON files using a bash script

jsonbashawk

提问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 reduceto apply it sequentially to all:

对于任意多个文件,使用reduce将其依次应用于所有文件:

##代码##

The -sswitch makes jqread the contents of the JSON files into a large array before handling them.

-s开关使jqJSON 文件的内容在处理它们之前读取到一个大数组中。