英文:
Filtering out sections in nested object
问题
以下是您要的翻译的内容:
{
  "foo": {},
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}
英文:
Given the following json:
{
  "foo": {},
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    },
    "b": {
      "tags": [
        "x"
      ],
      "cycle": null
    }
  },
  "baz": {
    "c": {
      "tags": [
        "y"
      ],
      "cycle": null
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}
I'd like to drop all objects in the top-level object which have "cycle == null". When filtering for "cycle", I don't know how to access fields from earlier filters:
$ jq '.[] | .[] | select(.cycle != null)' data.json
{
  "tags": [
    "x",
    "y"
  ],
  "cycle": "simple"
}
{
  "tags": [
    "x",
    "y",
    "z"
  ],
  "cycle": "complex"
}
I'd like to keep the structure of the matching entries, something like this:
{
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}
I was hoping to write something like this jq '.*.*. | select(.cycle != null)' so that I wouldn't need to manually re-assemble the original structure, but didn't understand wildcards.
答案1
得分: 1
.[] |= …(或 map_values(…))允许您操作对象的内容,而不会丢失外部结构。嵌套使用两次可以深入到两个级别。select(.cycle != null) 是您的主要筛选条件,但我还添加了 select(. != {}) 在中间级别,因为您的期望输出不包括 "foo": {}。
jq '.[] |= (.[] |= select(.cycle != null) | select(. != {}))'
{
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}
英文:
.[] |= … (or map_values(…)) lets you manipulate the contents of objects without losing the outer structure. Nest it twice to go two levels deep. select(.cycle != null) is your main filter, but I've also added select(. != {}) on the intermediate level as your desired output didn't include "foo": {}.
jq '.[] |= (.[] |= select(.cycle != null) | select(. != {}))'
{
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论