0

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 2

1

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:

jq '
  reduce (input.veg | to_entries)[] as $e (.; .veg[$e.key] += $e.value)
' file1.json file2.json
{
  "veg": {
    "trolley": [
      "potato",
      "lettuce",
      "tomato"
    ],
    "total_items": [
      1,
      2
    ]
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

A more hard-coded way of achieving the desired output could look like:

jq -s '{ 
    veg: {
        trolley: ([ .[].veg.trolley ] | add),
        total_items: ([ .[].veg.total_items ] | add),
    }
}' input1 input2

For each key, loop over the objects, create an array with all the values, and add them together

{
  "veg": {
    "trolley": [
      "potato",
      "lettuce",
      "tomato"
    ],
    "total_items": [
      1,
      2
    ]
  }
}

1 Comment

This works, but prefer the "simplicity" of the original approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.