使用 JQ 获取包含 JSON 中特定键的所有值的数组

Get array with all values for certain key in JSON wih JQ

假设我有以下 JSON:

{
  "a": 0,
  "b": "c",
  "d": {
    "e": {
      "f": "g",
      "comments": {
        "leading": "Lorem ipsum"
      },
      "h": {
        "i": {
          "j": [
            1,
            2
          ]
        },
        "comments": {
          "trailing": "dolor sit"
        }
      }
    },
    "comments": {
      "leading": "amet."
    }
  }
}

我想得到一个数组,其中包含名为 comments 的所有字段的值(可以嵌套在任何级别)。所以,在这种情况下,我想得到:

[
  {
    "leading": "Lorem ipsum"
  },
  {
    "trailing": "dolor sit"
  },
  {
    "leading": "amet."
  }
]

数组的顺序无关紧要。

jq 如何实现?我只用它做了一些基本的事情,还没有做出任何接近我需要的东西。

提前致谢☺️

您可以使用getpath功能。使用 paths 识别通向 .comments 的所有路径并获取路径的值

jq '[ getpath ( paths | select( .[-1] == "comments" ) ) ]'

或者使用递归下降过滤包含.comments的对象并获取其值

jq '[ recurse | select(has("comments")?).comments ]'