Assuming there is a json file:
{
\"columns\": {
\"id\": {
\"required\": true,
\"type\": \"integer\"
},
\"name\": {
\"required
Use alternative operator (//):
$ jq '.columns.description | .required // false' file
false
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.
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 ;
.)