如何使用 jq 从特定嵌套级别删除或忽略值

How to remove or ignore values from certain nesting level with jq

我有一个嵌套很深的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 并且不需要水平滚动 and/or 换行,但不需要较长的垂直滚动。

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

.hits.hits[] |= {id}

Online demo

I want to remove all items from a certain level of nesting

这是一个针对任何给定级别执行此操作的函数,$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
}