1

查询某些文档时,我想在层次结构中选择项目,但要保留结构中的父名称。例如,在查询 aws 数据库成员时,我可以使用:

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

要从:

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

至:

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

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

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

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

4

1 回答 1

1

语境

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

解决方案

例子

假设以下示例数据集...

    {
        "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"
                    }
                ]
            }
        ]
    }

... 以下 jmespath 查询 ...

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

...产生以下结果...

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

陷阱

  • 这种方法不会产生数据库名称作为 OP 中要求的对象键
于 2019-03-23T05:32:27.760 回答