jq:根据键从数组中删除对象

jq: Delete objects from an array based on its key

我想使用 jq 从数组中删除其键不对应于定义值的所有对象。

这是我的 JSON:

{
  "name": "config1",
  "children": [
    {
      "customer": {
        "name": "cust1"
      }
    },
    {
      "filter": {
        "name": "test1"
      }
    },
    {
      "filter": {
        "name": "test2"
      }
    },
    {
      "context": {
        "id": "1"
      }
    }
  ]
}

例如,我想删除所有键不是“filter”的对象。期望的输出:

{
  "name": "config1",
  "children": [
    {
      "filter": {
        "name": "test1"
      }
    },
    {
      "filter": {
        "name": "test2"
      }
    }
  ]
}

我试过了

jq 'del(.children[] | with_entries(select(.key != "filter")))'

但是会出现以下错误:

jq: error (at <stdin>:1): Invalid path expression near attempt to iterate through ["customer"]

您可以使用to_entries函数,例如

jq 'del(.children[] | select( to_entries[] | .key != "filter"))'

Demo

jq 'del(.children[] | select(.filter == null))'

检查一下online