简体   繁体   English

使用bash脚本合并JSON文件

[英]Merging JSON files using a bash script

I am very new to bash scripting. 我是新手来编写脚本。 I attempted to write a script that merges several json files. 我试图编写一个合并多个json文件的脚本。 For example: 例如:

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 = $0} {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? 有任何想法吗?

Handling JSON with awk is not a terribly good idea. 使用awk处理JSON并不是一个非常好的主意。 Arbitrary changes in meaningless whitespace will break your code. 无意义的空白中的任意更改将破坏您的代码。 Instead, use jq ; 相反,使用jq ; it is made for this sort of thing. 这是为了这种事情。 To combine two objects, use the * operator, ie, for two files: 要组合两个对象,请使用*运算符,即两个文件:

jq -s '.[0] * .[1]' file1.json file2.json

And for arbitrarily many files, use reduce to apply it sequentially to all: 对于任意多个文件,使用reduce将其顺序应用于所有文件:

jq -s 'reduce .[] as $item ({}; . * $item)' json_files/*

The -s switch makes jq read the contents of the JSON files into a large array before handling them. -s开关使jq在处理之前将JSON文件的内容读入大型数组。

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

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