Search code examples
jsonmatrixmultidimensional-arrayjqdimensions

jq: Get dimensions of 2d array


I'd like to retrieve the dimensions of a 2D array with jq.

test.json:

{
  "data": [
    [1,2,3,4],
    [5,6,7,8]
  ]
}

I can get the major dimension:

$ jq < test.json '.data | length'
2

I can get the minor dimension:

$ jq < test.json '.data[0] | length'
4

I would like to get both at once, ie: (does not work, expected output)

$ jq < test.json '.data | [length, .[0] ???? ]'
[
  2,
  4
]

Is there any way to produce this expected output with jq?


Solution

  • Pipe each separate dimension into length:

    $ echo '{
      "data": [
        [1,2,3,4],
        [5,6,7,8]
      ]
    }' | jq '.data | [length, (.[0] | length)]'
    [
      2,
      4
    ]
    

    The filter could also be written as

    .data | [., .[0]] | map(length)