Get or default function in JQ?

You can use the alternative operator (//) in this particular case.

$ jq '.columns.description | .required // false' file
false

For a fail-safe, generally applicable approach, see peak's answer.


If the field "required" does not exist, it should return the default value false.

To implement that functionality literally, you would use has/1 rather than //, e.g.:

   .columns.id
   | if has("required") then .required else false end

If the .required field is known never to be specified as null, then the two techniques (using has as above and using // false) are equivalent.

getOrDefault/2

You'd almost surely never define such a function, but since you ask:

def getOrDefault($key; $default):
  if has($key) then .[$key] else $default end;

(NB: The argument separator in jq is ;.)

Tags:

Json

Jq