I need to output in a single column the value of a field A if it's not null or the value of field B if not null or nothing if both A and B are null.
When I just had filed A to test I wrote this which worked ok
try .fieldA catch ""
But now as I need to take field B if A is null I tried those, and nothing worked
try .fieldA catch try .fieldB catch "" => this only returned empty values ever
try (.fieldA or .fieldB) catch "" => this one outputs true or false, 2 resultst instead of 1
try (.fieldA,.fieldB) catch "" => this one outputs both A and B if both are not nulll, so 2 resultst instead of 1
I'd like the try to stop evaluating whenever the first result is not null
Thanks
Use the alternate operator //, which takes the second alternative if the first is null or false, and empty for the "nothing" result.
If accessing any field might fail, additionally use the optional operator ? on those fields.
{
"fieldA": "A1 present",
"fieldB": "B1 present",
"fieldC": "irrelevant"
}
{
"fieldB": "B2 present",
"fieldC": "irrelevant"
}
{
"fieldA": "A3 present",
"fieldC": "irrelevant"
}
{
"fieldC": "irrelevant"
}
jq '.fieldA // .fieldB // empty'
"A1 present"
"B2 present"
"A3 present"
Addressing @peak's "warning": If you want to capture a filed that has the explicit boolean value false, while not capturing it if it is either missing or explicitly set to null, you can use values which selects non-null values only, and first to retrieve the first one that exists among a given stream of alternatives:
{
"fieldA": "A1 present",
"fieldB": "B1 present",
"fieldC": "irrelevant"
}
{
"fieldA": false,
"fieldB": "B2 present",
"fieldC": "irrelevant"
}
{
"fieldA": null,
"fieldB": "B3 present",
"fieldC": "irrelevant"
}
{
"fieldB": "B4 present",
"fieldC": "irrelevant"
}
{
"fieldC": "irrelevant"
}
jq 'first(.fieldA, .fieldB | values)'
"A1 present"
false
"B3 present"
"B4 present"
Using this approach, there's no need to provide the explicit empty case. However, if you want to have a default fallback, add it as the last item in the stream, e.g. first(.fieldA, .fieldB, "" | values).
jq's // operator has quite complicated semantics (*)
and in particular, when evaluating E // F, no distinction is made between E being null, false, or the empty stream.
Also, given an object as input, the expression .x will evaluate to the JSON value null if the key "x" is explicitly
specified as null or if the key "x" is not present at all.
Thus, assuming an object has been given as input, if we want .fieldA if .fieldA is non-null, and otherwise .fieldB if .fieldB is non-null, and otherwise the string "missing", then we would have to write something along the lines of:
if .fieldA != null then .fieldA
elif .fieldB != null then .fieldB
else "missing"
end
Simply replace "missing" by empty to achieve the objective stated in the original question.
(*) See the jq FAQ for complete details.