How to select a value, which is optional – using jq

This is how I am trying to ouput the message of an array element using jq

echo '{ errors: [{ "code": "INVALID", "message": "message" }] }' | jq -r '.errors[0].message'

But errors is an optional value. If there is no error, the field is missing. How do I have to handle the optional value correctly in jq?

So in the example the result is message and if there is no error, the result is empty.

>Solution :

You can use an if … then … else … end expression (see the manual) checking the existence of a field using has (see the manual):

… | jq -r 'if has("errors") then .errors[0].message else "no errors" end'

Alternatively, use the alternative operator // which is triggered on null or false (see the manual):

… | jq -r '.errors[0].message // "no errors"'

If your code would run into an exception, you can also equip the test with the error suppression operator ? (see the manual), which is not necessary with your sample code as it evaluates to null without errors if the .errors field was missing (see the manual: "it produces the value at the key, or null if there’s none present."):

… | jq -r '(.errors[0].message)? // "no errors"'

As @SUTerliakov pointed out, you can use empty anywhere in these examples instead of (the dummy string) "no errors" if you want no result at all on success.

Leave a Reply