Merging JSON files using a bash script -


i new bash scripting. attempted write script merges several json files. example:

file 1:

{   "file1": {      "foo": "bar"   } } 

file 2:

{   "file1": {      "lorem": "ipsum"   } } 

merged file:

{   "file1": {     "foo": "bar"   },   "file2": {     "lorem": "ipsum"   } } 

this came 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 feel there better way of doing this. ideas?

handling json awk not terribly idea. arbitrary changes in meaningless whitespace break code. instead, use jq; made sort of thing. combine 2 objects, use * operator, i.e., 2 files:

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

and arbitrarily many files, use reduce apply sequentially all:

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

the -s switch makes jq read contents of json files large array before handling them.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -