3

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?

4 Answers 4

4

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
    ]
    $
    
Sign up to request clarification or add additional context in comments.

Comments

2
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.

1 Comment

A little overkill for the problem but +1 anyway
1

Yet another way

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

Demo

1 Comment

Same idea; jq -s '[.[][]]'
1

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]

Comments

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.