python - 根据作为字典的键减少字典数组
问题描述
我正在寻找一个 jq 表达式,可以通过将它们分组到“标签”上来减少 json。我希望输出有一个共享相同标签的目标列表。
我尝试使用 group_by 和 reduce 的一些组合,但无法得到我想要的。
输入:
[{
"targets": [
"host1"
],
"labels": {
"platform": "VMware",
"os": "Windows",
"datacenter": "dc1",
"environment": "Production"
}
},{
"targets": [
"host2"
],
"labels": {
"platform": "VMware",
"os": "Windows",
"datacenter": "dc1",
"environment": "Production"
}
},
{
"targets": [
"host3"
],
"labels": {
"platform": "VMware",
"os": "Windows",
"datacenter": "dc2",
"environment": "Production"
}
}
]
输出:
[{
"targets": [
"host1",
"host2"
],
"labels": {
"platform": "VMware",
"os": "Windows",
"datacenter": "dc1",
"environment": "Production"
}
},
{
"targets": [
"host3",
],
"labels": {
"platform": "VMware",
"os": "Windows",
"datacenter": "dc2",
"environment": "Production"
}
}
]
PS 示例输入没有“标签”中的所有键,并且该列表可能会有所不同。
解决方案
如果您的要求更清晰,特别是如果您的示例满足mcve指南,这将很有帮助。但是,以下查询确实符合您的规范的一种解释:
group_by(.labels)
| map( { labels: (.[0].labels),
targets: (map(.targets)|add)} )
推荐阅读
- python - 抓取 Kickstarter 但遇到 HTTP 错误 404:未找到
- c# - 从谷歌电子表格获取剪贴板数据
- php - SQLSTATE [23000]:违反完整性约束:1062 键 'users_melli_unique' 的重复条目 '0430142821'
- python - 如何在pptx python的表格单元格中添加超链接?
- swift - TableViewCell 中的 ProgressView 在滚动时会出现奇怪的圆角
- excel - 从 com 端口读取串行数据到 excel 的第一个字符丢失/丢失
- python - 用于 Django 的嵌套序列化程序以嵌套子字段
- python - Cuda CascadeClassifier detectMultiScale 输出不可读
- python - TensorFlow 和 Keras 在 Keras 优化器方面的问题
- azure-active-directory - Microsoft Graph User.Read