【问题标题】:jq: Get dimensions of 2d arrayjq:获取二维数组的维度
【发布时间】:2021-03-02 09:32:27
【问题描述】:

我想用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 产生这个预期的输出?

【问题讨论】:

    标签: json matrix multidimensional-array jq dimensions


    【解决方案1】:

    下面是一个严格规则的 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]

    严格规律

    为了目前的目的,假设一个“矩阵”是严格规则的,如果它的条目都不是数组,并且 当且仅当对应的 n 维矩阵是严格规则时,n 维 JSON 数组才是严格规则的。

    为了检查一个 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);
    

    【讨论】:

      【解决方案2】:

      将每个单独的维度导入length

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

      过滤器也可以写成

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

      【讨论】:

      • 没有括号,表达式将等同于.data | [ (length, .[0] ) | length]
      猜你喜欢
      • 2011-11-14
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多