With jq
command, I want to merge multiple json files.
But I have no idea how to achieve below expectation.
thanks in advance
a.json
{
"key1": {
"key2": [
1,
2
]
},
"key3": "aaa"
}
b.json
{
"key1": {
"key2": [
3,
4,
5
]
},
"key4": "bbb"
}
expected result
{
"key1": {
"key2": [
1,
2,
3,
4,
5
]
},
"key3": "aaa",
"key4": "bbb"
}
2
Answers
jq -s 'reduce .[] as $item ({}; . + ($item | with_entries(if .key == "key1" then .value = (.value + $item.key1) else . end)))' a.json b.json
The problem is, that you want to merge like
*
would, but treat colliding arrays like+
would. You could prepare those arrays such that merging with*
will eventually work as desired, e.g. by pre-processing the addition, and storing it in the last affected array.Demo
Alternatively, use another JSON processor that provides such merging techniques. For example, mikefarah/yq implements a
*+
operator that "merges objects, but appends arrays". Note thatyq
is primarily a YAML processor (so the manual is focused around YAML examples) but it can also handle JSON input/output (if not clear from the filename extensions, use the explicit-pj -oj
flags).