I’m trying to combine two json files with arrays in common using jq (example below):
file1.json
{
"veg": {
"trolley": [
"potato"
],
"total_items": [
1
]
}
}
file2.json
{
"veg": {
"trolley": [
"lettuce",
"tomato"
],
"total_items": [
2
]
}
}
Desired output:
{
"veg": {
"trolley": [
"potato",
"lettuce",
"tomato"
],
"total_items": [
1,
2
]
}
}
I appreciate the json seems a bit of a poor example, I’m just trying to add in some numbers (my data contains numbers and strings).
If I do jq -s ‘add’, the results get overwritten; map and flatten yield similar results, if I use "|= . +" I end up with the same value in all the arrays.
Any help would be much appreciated and my apologies in advance if this has been resolved previously (I promise I looked!).
2
Answers
Do you just want to add up the individual arrays without removing duplicates? Do you know the parent field names beforehand? Can the top-level field name also be dynamic?
Answering all of them with no could lead to:
A more hard-coded way of achieving the desired output could look like:
For each key, loop over the objects, create an array with all the values, and
add
them together