jasonleonhard
jasonleonhard

Reputation: 13907

jq combine fields from array of objects in 2 json files into 3rd json file

file1.json

[
  {
    "a": "a",
    "b": "b"
  },
  {
    "a": "a",
    "b": "b"
  }
]

file2.json

[
  {
    "c": "c"
  },
  {
    "c": "c"
  }
]

desired output: file3.json

[
  {
    "a": "a",
    "b": "b",
    "c": "c"
  },
  {
    "a": "a",
    "b": "b",
    "c": "c"
  }
]

Upvotes: 0

Views: 86

Answers (1)

peak
peak

Reputation: 116910

For this type of problem, transpose (think zip) can often be used to produce compact solutions. In the present case:

jq -s 'transpose | map(add)' file1.json file2.json

jq's transpose can also be used with arrays that are not of the same length.

Upvotes: 1

Related Questions