简体   繁体   中英

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 StackName s for stacks that do NOT have a Tags value "Key": "Joe Shmo" ? So the result would return simply hello-man .

.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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM