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
Post a Comment