Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading