在JMESPath查询中保留层次结构

时间:2017-06-02 02:17:37

标签: json jmespath

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

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

来自:

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

要:

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

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

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

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

1 个答案:

答案 0 :(得分: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中的要求将数据库名称作为对象关键字生成