I want to have the output of either true or false. I have this syntax
.[] | (if (select(.displayName=="display")) then "yes" else "no" end)
This is the json source
[{"displayName":"display","message":"bla bla"}, {"displayName":"test","message":"bla bla"}]
I only need to query against the array and if the value im looking for exists in one of them I need the output to be "yes", and if it doesnt a "no". So a single output value is what I am looking for.
This evaluates to "yes"
, however, if the value display is not present in the json, it does not output "no"
, its just empty. Can anyone tell me why?
Here is a snippet to try: https://jqplay.org/s/WKcZh91hk8L
CodePudding user response:
The idea is right, but you shouldn't be using select
for this. The way select works is by evaluating the boolean expression provided inside (..)
and returning the object, if the expression evaluates to true and skip the object from being considered/printed on false.
On your code, for the object that evaluates to false, select is evaluated as select(false)
which as explained above returns nothing - this is not evaluated to boolean false condition. i.e. the return value of select is not a boolean value.
To use explicit boolean conditions, drop the select from expression and to summarise the result to a single value do something like below
if ( [ .[] | .displayName == "display" ] | any ) then "yes" else "no" end
Demo on jqplay
The way this works, is any
can evaluate an array of boolean values and produces true as output if any of the elements of the array are true. We collect the match condition results to the array and apply any
on it. i.e. [true, false]
evaluates to true
, thereby printing yes
only once