[英]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.