I have a json array response below,
[
{
"user": {
"login": "TOM",
},
"body": "",
"state": "APPROVED",
},
{
"user": {
"login": "JERRY",
},
"body": "",
"state": "APPROVED",
},
{
"user": {
"login": "ANDY",
},
"body": "",
"state": "REJECTED",
}
]
I am working on code to check if only when user Jerry exists and has state APPROVED I should set a variable value as true else it should be false.
In above case I should get true and in either of the below cases it should be false
[
{
"user": {
"login": "TOM",
},
"body": "",
"state": "APPROVED",
},
{
"user": {
"login": "JERRY",
},
"body": "",
"state": "REJECTED",
},
{
"user": {
"login": "ANDY",
},
"body": "",
"state": "REJECTED",
}
]
or
[
{
"user": {
"login": "TOM",
},
"body": "",
"state": "APPROVED",
},
{
"user": {
"login": "ANDY",
},
"body": "",
"state": "REJECTED",
}
]
I tried below code but I am not able to address both the condition
hasJerry = false
if [ (jq -r '.[].user.login | index("JTHOM949")') && (jq -r '.[].state' == "APPROVED") ]; then
hasJerry = true
fi
can someone help me to fix this script.
2
Answers
You can have jq output
true
orfalse
, thus set the variable directly. Within jq, you can useany
to find "at least one item" that matches your criteria.Demo
Note that your Bash script has errors (e.g. whitespace around
=
with the variable assignment), as does your (sample) JSON input (e.g. commas after the last field in an object). Please correct them first.Instead of returning the raw True or False strings, you could test the return status: