Assuming there is a json file:
{
"columns": {
"id": {
"required": true,
"type": "integer"
},
"name": {
"required": false,
"type": "string"
},
"description": {
"type": "string"
}
}
}
I want to use jq to get the value "required" field for each column. If the field "required" does not exist, it should return the default value false.
Specifically:
jq '.columns.id | getOrDefault("required", false)' # true
jq '.columns.name | getOrDefault("required", false)' # false
jq '.columns.description | getOrDefault("required", false)' # false
How to implement this magic getOrDefault() function in jq?
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 ;.)
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With