Filter output based on the existence of multiple k

2020-02-10 07:40发布

问题:

Using JMESPath, is it possible to filter output based on the existence of multiple key/value pairs within the input?

From the example JSON below, what I'd like to do is extract only the objects that contain these key/value pairs within Tags -

Environment / ABC
Project / Project2

The closest I can get is to select a single matching Tag, but I require the rest of the object too, and I also need to match against the other key/value pair -

Stacks[*].Tags[?Key=='Environment' && Value=='ABC']

Here is some exaple JSON input -

{
    "Stacks":  [
        {
            "StackId": "abc123",
            "Tags": [
                {
                    "Value": "Project 1",
                    "Key": "Project"
                },
                {
                    "Value": "ABC",
                    "Key": "Environment"
                }
            ],
            "CreationTime": "2016-07-20T14:49:27.891Z",
            "StackName": "TestStack1",
            "NotificationARNs": [],
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        },
        {
            "StackId": "xyz123",
            "Tags": [
                {
                    "Value": "Project 1",
                    "Key": "Project"
                },
                {
                    "Value": "XYZ",
                    "Key": "Environment"
                }
            ],
            "CreationTime": "2016-07-20T14:49:27.891Z",
            "StackName": "TestStack2",
            "NotificationARNs": [],
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        },
        {
            "StackId": "asd123",
            "Tags": [
                {
                    "Value": "Project 2",
                    "Key": "Project"
                },
                {
                    "Value": "ABC",
                    "Key": "Environment"
                }
            ],
            "CreationTime": "2016-07-20T14:49:27.891Z",
            "StackName": "TestStack3",
            "NotificationARNs": [],
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        }
    ]
}

And here is the output that I require -

{
    "StackId": "asd123",
    "Tags": [
        {
            "Value": "Project 2",
            "Key": "Project"
        },
        {
            "Value": "ABC",
            "Key": "Environment"
        }
    ],
    "CreationTime": "2016-07-20T14:49:27.891Z",
    "StackName": "TestStack3",
    "NotificationARNs": [],
    "StackStatus": "CREATE_COMPLETE",
    "DisableRollback": false
}

回答1:

You can use nested filters:

Stacks[? Tags[? Value=='ABC' && Key=='Environment']]



标签: jmespath