jq:获取二维数组的维度

jq: Get dimensions of 2d array

我想用 jq 检索二维数组的维度。

test.json:

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

我可以得到主维度:

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

我可以得到次要维度:

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

我想同时获得两者,即:(不起作用,预期输出)

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

有什么方法可以用 jq 产生这个预期的输出吗?


将每个单独的维度通过管道传输到 length:

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

过滤器也可以写成

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

这是一个严格规则的 n 维数组的通用解决方案:

.data | [recurse( .[0]? | select(type=="array")) |  length]

有关严格规律性概念的​​更多信息,请参阅下文。

作为函数

def rho: [recurse( .[0]? | select(type=="array")) |  length];

[ [[1,1],[2,2]], [[1,1],[2,2]], [[1,1],[2,2]]] | rho

会产生:[3,2,2]

严格规律

为了目前的目的,假设一个“矩阵”是严格正则的,如果它的 none 个条目是一个数组,并且 一个 n 维 JSON 数组是严格正则的当且仅当相应的 n 维矩阵是严格正则的。

要检查 JSON 数组在这个意义上是严格正则的,我们可以定义 is_strictly_regular(使用上述 rho 的定义)如下:

# Check whether the input has precisely the specified
# dimensions, and no additional arrays.
# It is assumed that $dimensions is an array of non-negative integers.
# If $dimensions is [], then return type!="array".
def strictcheck($dimensions):
  if type == "array"
  then ($dimensions|length) > 0
       and length == $dimensions[0]
       and all(.[]; strictcheck($dimensions[1:]))
  else $dimensions == []
  end;

def is_strictly_regular:
  rho as $d
  | strictcheck($d);