[英]Remove key from json based on condition with jq
我知道有很多類似的解決方案,但沒有一個符合我的情況。 我有這個 json:
{
"page": 1,
"per_page": 20,
"total": 3,
"saved_objects": [
{
"type": "dashboard",
"id": "f3ea5f20-e773-11ea-8cae-c1046c8b1215"
},
{
"type": "dashboard",
"id": "5c071f30-e797-11ea-8cae-c1046c8b1215"
},
{
"type": "dashboard",
"id": "644a15c0-e79d-11ea-8cae-c1046c8b1215"
}
]
}
如果 id == "f3ea5f20-e773-11ea-8cae-c1046c8b1215" 或 id == "5c071f30-e797-11ea-8cae-c1046c8b1215" 我想刪除這個鍵,所以 output 應該是:
{
"page": 1,
"per_page": 20,
"total": 3,
"saved_objects": [
{
"type": "dashboard",
"id": "644a15c0-e79d-11ea-8cae-c1046c8b1215"
}
]
}
我試過:
jq 'select(.saved_objects[].id != "f3ea5f20-e773-11ea-8cae-c1046c8b1215" and .saved_objects[].id != "5c071f30-e797-11ea-8cae-c1046c8b1215")'
和很多變化,但沒有任何效果。 我究竟做錯了什么?
謝謝你的幫助。
你很接近。
jq '.saved_objects=(
.saved_objects[] |
select (.id != "f3ea5f20-e773-11ea-8cae-c1046c8b1215"
and .id != "5c071f30-e797-11ea-8cae-c1046c8b1215"))
' file.json
如果黑名單比較長或者應該作為參數傳遞,下面的做法值得注意:
["f3ea5f20-e773-11ea-8cae-c1046c8b1215", "5c071f30-e797-11ea-8cae-c1046c8b1215"] as $blacklist
| .saved_objects |= map(select(.id | IN($blacklist[]) | not))
或者更簡潔:
["f3ea5f20-e773-11ea-8cae-c1046c8b1215", "5c071f30-e797-11ea-8cae-c1046c8b1215"] as $blacklist
| del(.saved_objects[] | select(.id | IN($blacklist[])))
另請注意|=
在上面的第一種方法中的使用。
我也很想發布基於不同方法( jtc
)的解決方案,只是為了了解替代方案:
1. 臨時解決方案是清除每個找到的元素的父元素:
bash $ <file.json jtc -pw'<f3ea5f20-e773-11ea-8cae-c1046c8b1215>[-1]' -w'<5c071f30-e797-11ea-8cae-c1046c8b1215>[-1]'
{
"page": 1,
"per_page": 20,
"saved_objects": [
{
"id": "644a15c0-e79d-11ea-8cae-c1046c8b1215",
"type": "dashboard"
}
],
"total": 3
}
bash $
2. 可能是一種更方便的方法,其中 ID 作為 JSON 數組傳遞:
bash $ ids='["5c071f30-e797-11ea-8cae-c1046c8b1215","f3ea5f20-e773-11ea-8cae-c1046c8b1215"]'
bash $ <file.json jtc -pw'[id]:<I>P:[-1]' -u"$ids" -u'<I>s'
{
"page": 1,
"per_page": 20,
"saved_objects": [
{
"id": "644a15c0-e79d-11ea-8cae-c1046c8b1215",
"type": "dashboard"
}
],
"total": 3
}
bash $
如果需要直接更新源文件(又名就地更新),則使用選項-f
,如下所示: jtc -pw'[id]:<I>P:[-1]' -u$ids -u'<I>s' -f file.json
附言。 正好我也是jtc
unix工具的開發者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.