Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter output based on the existence of multiple key/value pairs

Tags:

jmespath

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
}
like image 878
David Gard Avatar asked Jan 06 '17 10:01

David Gard


1 Answers

You can use nested filters:

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

like image 177
gdyuldin Avatar answered Dec 31 '22 20:12

gdyuldin