如何使用 JQ 合并两个简单的 JSON 数组

How to merge two simple JSON arrays together with JQ

我想合并到数组中。

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

# command 应该是什么?

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

解释:

  • flatten(1) 取消嵌套深度为 1 的数组。
  • -s 对所有项目(即两个列表)运行命令,而不是对每个项目单独运行。

另一种简单的方法,只使用 add:

jq -s 'add' input.json

[Documentation]


  • JqPlay Demo
  • 本地shell示例

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

另一种方式

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

Demo

c 选项打印到一行。 另外,如果你想合并两个数组并保持它们排序,你可以这样做:

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

例如,在下面的情况下仍然是有序的:

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