Mike
Mike

Reputation: 359

How can I filter for entries that do NOT contain a key-value pair within a nested array

Let's say I have the following JSON output:

{
 "Stacks": [
        {
            "StackName": "hello-world",
            "Tags": [
                {
                    "Key": "environment",
                    "Value": "sandbox"
                },
                {
                    "Key": "Joe Shmo",
                    "Value": "Dev"
                }
            ]
        },
        {
            "StackName": "hello-man",
            "Tags": [
                {
                    "Key": "environment",
                    "Value": "live"
                },
                {
                    "Key": "Tandy",
                    "Value": "Dev"
                }
            ]
        }
    ]
}

How would I write a jq query to grab all StackNames for stacks that do NOT have a Tags value "Key": "Joe Shmo"? So the result would return simply hello-man.

Upvotes: 1

Views: 53

Answers (2)

peak
peak

Reputation: 116740

.Stacks[]
| select( any(.Tags[]; .Key == "Joe Shmo" ) | not)
| .StackName

This checks for equality efficiently (any has short-circuit semantics), whereas contains would check for containment.

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157992

Using contains, like this:

jq -r '.Stacks[]|select(.Tags|contains([{"Key": "Joe Shmo"}])|not).StackName'

Note: -r removes the quotes from output, otherwise jq would print "hello-man" (within double quotes)

Upvotes: 0

Related Questions