在 JMESPath 查询中保留层次结构

Preserve hierarchy in JMESPath query

查询某些文档时,我想 select 项目在层次结构中向下,但在其他方面保留结构中的父名称。例如查询aws数据库成员时,我可以使用:

DBClusters[].DBClusterMembers[].[DBInstanceIdentifier,IsClusterWriter]

获取自:

{
    "DBClusters": [
        {
            "DatabaseName": "bazbar",
            "DBClusterMembers": [
                {
                    "IsClusterWriter": false,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 2,
                    "DBInstanceIdentifier": "foobar"
                },
    ...

收件人:

[
    [
        "foobar",
        false
    ],
    ...

但是我怎样才能得到以下响应:

{
    "bazbar": [
        [
             "foobar",
             false
        ],
        ...

即对于每个集群,提取 DatabaseName 作为成员列表的键名?

上下文

  • Jmespath查询
  • 如何生成保留对象嵌套的查询
  • 如何生成来自另一个对象键值对的值的动态对象键

解决方案

例子

Assuming the following sample dataset ...

    {
        "dbclusters": [
            {
                "databasename": "alpha",
                "dbclustermembers": [
                    {
                        "isclusterwriter": false,
                        "dbinstanceidentifier": "foobar"
                    }
                    ,{
                        "isclusterwriter": true,
                        "dbinstanceidentifier": "doobar"
                    }
                ]
            }
            ,{
                "databasename": "bravo",
                "dbclustermembers": [
                    {
                        "isclusterwriter": false,
                        "dbinstanceidentifier": "foobar"
                    }
                ]
            }
            ,{
                "databasename": "charlie",
                "dbclustermembers": [
                    {
                        "isclusterwriter": false,
                        "dbinstanceidentifier": "foobar"
                    }
                ]
            }
        ]
    }

... the following jmespath query ...

    @.dbclusters[].{"databasename":databasename
        ,"dbclustermembers":[dbclustermembers[*].isclusterwriter
        ,dbclustermembers[*].dbinstanceidentifier][]
        }

... produces the following result ...

    [
      {
        "databasename": "alpha",
        "dbclustermembers": [
          false,
          true,
          "foobar",
          "doobar"
        ]
      },
      {
        "databasename": "bravo",
        "dbclustermembers": [
          false,
          "foobar"
        ]
      },
      {
        "databasename": "charlie",
        "dbclustermembers": [
          false,
          "foobar"
        ]
      }
    ]

陷阱

  • 此方法不会按照 OP 中的要求生成数据库名称作为对象键
    • 截至撰写本文时 (2019-03-22),动态键在标准 Jmespath 中不可用
    • related Whosebug post