在JQ中获取或默认功能? [英] Get or default function in JQ?
问题描述
假设有一个json文件:
Assuming there is a json file:
{
"columns": {
"id": {
"required": true,
"type": "integer"
},
"name": {
"required": false,
"type": "string"
},
"description": {
"type": "string"
}
}
}
我想使用jq
来获取每一列的值"required"字段.如果字段"required"不存在,则应返回默认值false
.
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
.
特别是:
jq '.columns.id | getOrDefault("required", false)' # true
jq '.columns.name | getOrDefault("required", false)' # false
jq '.columns.description | getOrDefault("required", false)' # false
如何在jq
中实现此神奇的getOrDefault()函数?
How to implement this magic getOrDefault() function in jq
?
推荐答案
如果字段"required"不存在,则应返回默认值false.
If the field "required" does not exist, it should return the default value false.
要从字面上实现该功能,您可以使用has/1
而不是//
,例如:
To implement that functionality literally, you would use has/1
rather than //
, e.g.:
.columns.id
| if has("required") then .required else false end
如果永不将.required字段指定为null
,则两种技术(如上使用has
和// false
)是等效的.
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;
(注意:jq中的参数分隔符是;
.)
(NB: The argument separator in jq is ;
.)
这篇关于在JQ中获取或默认功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!