![](/img/trans.png)
[英]How can I filter for entries that do NOT contain a key-value pair within a nested array
[英]How can I remove a nested key-value pair, whose value has a deeper nested array with a specific value by using jq
我目前正在嘗試使用 jq 從 swagger json 文檔中過濾掉一些路徑值。
JSON 看起來像這樣:
{
"swagger": "2.0",
"info": {
"version": "1.0.2",
"title": "Some API"
},
"host": "example.com",
"basePath": "/",
"paths": {
"/api/companies": {
"get": {
"tags": [ "company-tag" ],
"responses": {
"200": {
"description": "OK",
"schema": { "$ref": "#/definitions/CompanyDTO" }
}
}
}
},
"/api/account": {
"get": {
"tags": [ "account-tag" ],
"operationId": "getAccount",
"responses": {
"200": {
"description": "OK",
"schema": { "$ref": "#/definitions/UserDTO" }
}
}
},
"post": {
"tags": [ "account-tag" ],
"operationId": "createAccount",
"responses": {
"200": {
"description": "OK",
"schema": { "$ref": "#/definitions/UserDTO" }
}
}
}
}
}
}
我想過濾路徑值,以便我只能獲取標簽數組中包含特定標簽的路徑。
例如:如果我想獲取帳戶標簽的路徑,則 JSON 在過濾后應該如下所示:
{
"swagger": "2.0",
"info": {
"version": "1.0.2",
"title": "Some API"
},
"host": "example.com",
"basePath": "/",
"paths": {
"/api/account": {
"get": {
"tags": [ "account-tag" ],
"operationId": "getAccount",
"responses": {
"200": {
"description": "OK",
"schema": { "$ref": "#/definitions/UserDTO" }
}
}
},
"post": {
"tags": [ "account-tag" ],
"operationId": "createAccount",
"responses": {
"200": {
"description": "OK",
"schema": { "$ref": "#/definitions/UserDTO" }
}
}
}
}
}
}
編輯
池上的第二個建議果然奏效了。 這是我的最終解決方案
如果我們假設給定路徑的所有方法( get
, post
等)共享相同的標簽,我們可以簡單地使用以下內容:
.paths |= with_entries( select( .value[].tags | index("account-tag") ) )
jqplay上的演示
如果該假設不成立,我們將需要在兩個級別進行過濾。
.paths |= with_entries(
.value |= with_entries(
select( .value.tags | index("account-tag") )
) |
select( .value | length > 0 )
)
jqplay上的演示
或者
.paths |= with_entries(
.value = (
.value |
with_entries(
select( .value.tags | index("account-tag") )
) |
select( length > 0 )
)
)
jqplay上的演示
(我討厭我必須在這里使用.value = (.value |... )
而不是.value |= (... )
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.