Search

Dark theme | Light theme

October 3, 2023

jq Joy: Flatten Arrays

jq is a powerful tool to work with JSON from the command-line. The tool has a lot of functions that makes our live easier. We can use the flatten function to flatten nested arrays into a single array. If we use the function without an argument the arrays are flattened recursively, resulting in a flat array with all elements. But we can also set the depth we want to flatten the array by passing an integer argument to the flatten function.

In the following example we use the flatten function without arguments to recursively flatten the array:

$ jq --null-input '[1, [2, 3], [[4]], 5] | flatten'
[
  1,
  2,
  3,
  4,
  5
]

We can pass an argument to the flatten function to indicate the depth to flatten the collection. In the following example we want to flatten only one level deep:

$ jq --null-input '[1, [2, 3], [[4]], 5] | flatten(1)'
[
  1,
  2,
  3,
  [
    4
  ],
  5
]

Written with jq 1.7.