Home > front end >  Combining multiple json arrays
Combining multiple json arrays

Time:12-16

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!).

CodePudding user response:

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
    ]
  }
}

CodePudding user response:

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
    ]
  }
}
  • Related