首页 > 解决方案 > 选择子子对象中的所有键

问题描述

我不明白 jq 是如何工作的。我正在努力,但我就是不明白。请参阅下面我现在如何创建 jq 查询。

所以这是我的 JSON,我只想提取所有子对象中的名称键

{
  "checkpassword": {
    "checkpassword": {
      "containers": [
        {
          "name": "checkpassword",
          "exists": "true",
          "running": "true"
        }
      ],
      "projectdir": "true",
      "nginxdef": "true"
    }
  },
  "reverse_proxy": {
    "reverse_proxy": {
      "containers": [
        {
          "name": "reverse_proxy",
          "exists": "true",
          "running": "true"
        }
      ],
      "projectdir": "true"
    }
  }
}

我放弃了自己尝试,我在浪费时间。我觉得很多用户都处于同样的情况。

请任何帮助表示赞赏。

.

注意:这就是我开发查询的方式:

root@priv  …/newProject   master  san_listProjects | jq -r '.[] | select( any(.name)'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select( any(.name)
jq: 1 compile error
 root@priv  …/newProject   master  san_listProjects | jq -r '.[] | select( any(".name")'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select( any(".name")
jq: 1 compile error
 root@priv  …/newProject   master  san_listProjects | jq -r '.[] | select( any("name")'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select( any("name")
jq: 1 compile error
 root@priv  …/newProject   master  san_listProjects | jq -r '.[] | select(any("name")'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select(any("name")
jq: 1 compile error
 root@priv  …/newProject   master  san_listProjects | jq -r '. | select(any("name")'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
. | select(any("name")
jq: 1 compile error
 root@priv  …/newProject   master  san_listProjects | jq -r '. | select(any(".name")'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
. | select(any(".name")
jq: 1 compile error
 root@priv  …/newProject   master  san_listProjects | jq -r '. | select(any(.name)'
jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
. | select(any(.name)
jq: 1 compile error

标签: jsonjq

解决方案


您尝试的问题既不存在.也不.[]让您访问嵌套在级别.name键的对象键。此外,所有函数)调用都缺少关闭。select

有多种方法可以完成这项工作。一种方法是映射通向name键的路径并获取该路径的值

(paths | select( .[-1] == "name")) as $path | getpath($path)

jqplay演示

或如评论中所述,只需使用内置的递归下降recurse并选择具有包含.name键的字段的对象

recurse | select(has("name")?).name

推荐阅读