I'm trying to use the following jq command to return a true output, if any of one of the condition is true in the list.
.Tags[] as $t| "aws:cloudformation:stack-name"| IN($t[])
Input
{
"Tags": [{
"Value": "INF-D-XX-SEC-OPNV-UW1",
"Key": "Name"
},
{
"Value": "INF-D-XX-CFS-StandardInfrastructure-UW1",
"Key": "aws:cloudformation:stack-name"
},
{
"Value": "sgOpenVPNAccess",
"Key": "aws:cloudformation:logical-id"
},
{
"Value": "UW1",
"Key": "Location"
},
{
"Value": "INF",
"Key": "Application"
},
{
"Value": "D",
"Key": "Parent Environment"
},
{
"Value": "arn:aws:cloudformation:us-west-1:111111:stack/INF-D-XX-CFS-StandardInfrastructure-UW1/1111-11-11e8-96fe-11",
"Key": "aws:cloudformation:stack-id"
},
{
"Value": "OPNV",
"Key": "ResourceType"
}
]
}
This gave me a list of returned boolean values back as the following,
--output--
true
false
false
false
false
false
false
I would like to return a single value true
if one of the
Key="aws:cloudformation:stack-name"
is detected and without given me a list of value back.
A very efficient solution (both with respect to time and space) is easy thanks to any/2
:
any(.Tags[]; .Key == "aws:cloudformation:stack-name")
This of course evaluates either to true
or false
. If you want true
or nothing at all, you could tack on // empty
to the above.
一个解决方案,从 .tags 构建一个布尔数组,然后使用any来聚合所有的布尔值
jq '.Tags | map( .Key == "aws:cloudformation:stack-name" ) | any '
if you're open for alternatives, here's also a simple one (based on unix utility jtc
):
bash $ <file.json jtc -w'[Key]:<^aws:cloudformation:stack-name$()>R' -T'true{$1}'
true
bash $ <file.json jtc -w'[Key]:<^blah$()>R' -T'true{$1}'
bash $
a little trick is: perform a RE match, while using a phony/empty group (at the end of RE), just ensure that interpolation kicks in for the template upon a successful match.
Building on the previous answer by @peak, as can't post comments, you can use the '-e' flag to jq to set the exit status so you can easily chain shell commands together. This avoids having to test for the returned string.
jq -e 'any(.Tags[]; .Key == "aws:cloudformation:stack-name")' json >/dev/null && echo 'Exists' || echo 'Missing'
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.