【问题标题】:How to remove or ignore values from certain nesting level with jq如何使用 jq 从某个嵌套级别删除或忽略值
【发布时间】:2020-08-14 16:54:15
【问题描述】:

我有一个深度嵌套的 JSON,它太大而无法查看;我想从某个嵌套级别中删除所有项目,最好使用jq

说,JSON 是:

{
  "paging": {
    "next": "items?page=12",
    "previous": "items?page=10"
  },
  "hits": {
    "total": 10200,
    "max_score": 1,
    "hits": [
      {
        "id": 1337,
        "really large struct 1": "with long and complexed nested values"
      },
      {
        "id": 1338,
        "really large struct 1": "with long and complexed nested values"
      }
    ]
  },
  "took": 11,
  "timed_out": false
}

在此示例中,我想省略 .hits.hits 下的所有内容,可以将其替换为省略号 (...) 或直接忽略它。一个不错的选择是在示例中仅呈现 id 值。

pagingtooktimed_oud 等字段是示例,可能会更改,或者是一个相当长且实用的列表,因此简单地将所有应该保留的内容列入白名单不是一种选择:我想要过滤掉某个深度而不显示它;不过,过滤某些列入黑名单(黑名单)的项目(例如删除所有 .hits.hits.*)是可以的。

我已经尝试过jq '.' | cut -c1-40,它不需要水平滚动和/或换行,但不需要长垂直滚动。

【问题讨论】:

    标签: json nested jq ellipsis


    【解决方案1】:

    我想从某个嵌套级别中删除所有项目

    这是一个对任何给定级别都执行此操作的函数,$n:

    def maxdepth($n):
      . as $in
      | reduce paths as $p (null;
           if ($p|length) > $n
           then .
           else ($in | getpath($p) ) as $v
           | if ($p|length) == $n
             then if (($v|type =="object") and ($v|length>1))
                  then setpath($p; "{...}" )
                  elif (($v|type == "array") and ($v|length>1))
                  then setpath($p; "[...]" )
                  else setpath($p; $v) 
                  end
             else setpath($p; $v) 
             end
           end) ;
    

    最大深度(2)

    使用您的示例,maxdepth(2) 产生:

    {
      "paging": {
        "next": "items?page=12",
        "previous": "items?page=10"
      },
      "hits": {
        "total": 10200,
        "max_score": 1,
        "hits": "[...]"
      },
      "took": 11,
      "timed_out": false
    }
    

    【讨论】:

    • 我不知道 jq 可以处理脚本和函数。您能否添加关于如何将此函数与 jq 一起使用的注释,或者必须使用 jq 之外的(perl?)解释器运行此函数?
    • 请参阅 jq 手册中的“定义函数”部分,例如stedolan.github.io/jq/manual/v1.6
    【解决方案2】:

    使用下面的程序更新.hits.hits 的所有成员以仅保留id 字段,我想这就是您要查找的内容。

    .hits.hits[] |= {id}
    

    Online demo

    【讨论】:

      猜你喜欢
      • 2017-03-14
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多