Chris Stryczynski
Chris Stryczynski

Reputation: 34041

How to combine two arrays by merging each object with jq?

How can I use jq to combine the two files above, into a single array, by merging each object?

I've found combine array of objects from two files with jq under specific key 1.4 but this is for a specific key.

I've tried:

jq -n '{ combined: (transpose | map(add)) }' a.json b.json  
jq: error (at <unknown>): Cannot iterate over null (null)

Input:

    ==> a.json <==
    [
      {
        "datetime": "2019-12-08 11:34"
      },
      {
        "datetime": "2019-12-08 11:35"
      },
      {
        "datetime": "2019-12-08 12:03"
      }
    ]

    ==> b.json <==
    [
      {
        "command": "cat test.txt"
      },
      {
        "command": "cat test2.txt"
      },
      {
        "command": "cat test3.txt"
      }
    ]

Desired output:

    [
      {
        "command": "cat test.txt",
        "datetime": "2019-12-08 11:34"
      },
      {
        "command": "cat test2.txt",
        "datetime": "2019-12-08 11:35"
      },
      {
        "command": "cat test3.txt",
        "datetime": "2019-12-08 12:03"
      }
    ]

Upvotes: 1

Views: 335

Answers (1)

oguz ismail
oguz ismail

Reputation: 50805

Just slurp them. -n is for null input, and is overkill for this trivial task.

jq -s 'transpose | map(add)' a.json b.json

Upvotes: 2

Related Questions