Mathieu Paturel
Mathieu Paturel

Reputation: 4500

How to merge two simple JSON arrays together with JQ

I want to merge to arrays together.

$ cat file.json
[1,2,3,4]
[5,6,7,8]
$ # command
[1,2,3,4,5,6,7,8]

What should # command be?

Upvotes: 3

Views: 2996

Answers (4)

Nicolas Kagami
Nicolas Kagami

Reputation: 140

The c option prints to one line. Also if you want to merge the two arrays and keep them sorted you can do this:

jq -cn '[inputs[]] | sort' file.json

For example, it will still be in order in the case below:

$ cat file.json
[1,2,3,5]
[4,6,7,8]
$ jq -cn '[inputs[]] | sort '  file.json
[1,2,3,4,5,6,7,8]

Upvotes: 1

pmf
pmf

Reputation: 36033

Yet another way

jq -n '[inputs[]]' file.json

Demo

Upvotes: 1

Mathieu Paturel
Mathieu Paturel

Reputation: 4500

jq -s 'flatten(1)' file.json

Explanation:

  • flatten(1) de-nests arrays with depth of 1.
  • -s runs the command on all the items (ie. both lists) rather than each item independently.

Upvotes: 2

0stone0
0stone0

Reputation: 43904

Another simple way, using just add:

jq -s 'add' input.json

[Documentation]


  • JqPlay Demo
  • Local shell example

    $ cat input.json
    [1,2,3,4]
    [5,6,7,8]
    $
    $ jq -s 'add' input.json
    [
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8
    ]
    $
    

Upvotes: 4

Related Questions