我正在尝试编辑 OpenAPI 规范,将所有参数更改为可空。参数定义如下:
{
"name": "foo",
"required": true,
"type": "string"
}
它们包含在一个parameters
数组中,可以位于文档中的任何位置。我需要的是附加"x-nullable": true
到包含属性的任何参数type
。
样本数据:
{
"parameters": [
{"notype": "x"},
{"type": "x"}
],
"foo": {
"parameters": [
{"type": "y"}
]
},
"bar": {
"baz": {
"parameters": [
{"type": "z"}
]
}
}
}
期望输出:
{
"parameters": [
{"notype": "x"},
{
"type": "x",
"x-nullable": true
}
],
"foo": {
"parameters": [
{
"type": "y",
"x-nullable": true
}
]
},
"bar": {
"baz": {
"parameters": [
{
"type": "z",
"x-nullable": true
}
]
}
}
}
我能得到的最接近的答案是:
.. | (.parameters[] | select(.type)) += {"x-nullable":true}
它成功更改了我的测试文档中的一项,但结果不一致,并且似乎是基于我为样本数据选择的结构。
以下
jq
表达式将更新应用于文档中找到的所有键的值parameters
。假设parameters
键始终引用数组。更新将分配true
给x-nullable
具有键的所有数组元素的键type
。递归是通过
walk()
(递归地将表达式应用于文档中的每个值)而不是递归下降运算符..
(递归地提取文档的每个值)完成的。select(has("type"))
使用选择具有字段的对象更安全type
,因为使用会错过值为或 的select(.type)
对象。type
false
null
对问题中的示例文档进行测试: