使用 JQ 对数组对象进行分组并删除重复项
给定 json,我需要按键 userName
对对象进行分组userClientDetailDTOList
跨所有站点 -> 建筑物 -> 楼层,并删除任何重复的 MAC 地址。
我已经能够使用 jq 表达式 -
[.billingDetailPerSiteDTOList[].billingDetailPerBuildingDTOList[].billingDetailsPerFloorDTOList[].userClientDetailDTOList[] ] | 来做到这一点group_by(.用户名) | map((.[0]|del(.linkedMacs)) + { linkedMacs: (map(.linkedMacs[]) | unique) })
这按 userName
进行分组,并且还会删除重复的macs
属于特定用户。这会产生一个列表
[
{
"userName": "1",
"associatedMacs": [
"3:3:3:3:3:3",
"5:5:5:5:5:5"
]
},
{
"userName": "10",
"associatedMacs": [
"4:4:4:4:4:4",
"6:6:6:6:6:6"
]
},
{
"userName": "2",
"associatedMacs": [
"1:1:1:1:1:1",
"2:2:2:2:2:2"
]
},
{
"userName": "3",
"associatedMacs": [
"2:2:2:2:2:2"
]
}
]
问题:
- 表达式可以简化吗?
- 如何删除所有用户的重复 MAC 地址?用户
2
和3
的 MAC 地址2:2:2:2:2:2
重复
Given the json, I need to group by key userName
the object userClientDetailDTOList
across all sites->buildings->floors and remove any duplicate mac addresses.
I have been able to do it using jq expression -
[.billingDetailPerSiteDTOList[].billingDetailPerBuildingDTOList[].billingDetailsPerFloorDTOList[].userClientDetailDTOList[] ] | group_by(.userName) | map((.[0]|del(.associatedMacs)) + { associatedMacs: (map(.associatedMacs[]) | unique) })
This groups by userName
and also removes duplicate macs
belonging to particular user. This results in a list as
[
{
"userName": "1",
"associatedMacs": [
"3:3:3:3:3:3",
"5:5:5:5:5:5"
]
},
{
"userName": "10",
"associatedMacs": [
"4:4:4:4:4:4",
"6:6:6:6:6:6"
]
},
{
"userName": "2",
"associatedMacs": [
"1:1:1:1:1:1",
"2:2:2:2:2:2"
]
},
{
"userName": "3",
"associatedMacs": [
"2:2:2:2:2:2"
]
}
]
Questions:
- Can the expression be simplified?
- How do I remove duplicate mac addresses across all users? The mac address
2:2:2:2:2:2
is repeated for users2
and3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该过滤器实际上已尽其所能。如果您确实愿意,您仍然可以将
del(.linkedMacs)
更改为{userName}
以获得肯定的定义,并且(...) + {...}< /code> 到
{userName: …, AssociatedMacs: …}
以避免添加,导致
Demo
至于第二个问题,如果您将输入视为 IP 上的
INDEX
,那么您基本上可以重用之前的代码(当然,独特的
部分不再需要)演示
The filter is practically as good as it can get. If you really wanted to, you could still change
del(.associatedMacs)
to{userName}
for a positive definition, and(…) + {…}
to{userName: …, associatedMacs: …}
to avoid the addition,resulting in
Demo
As for the second question, if you treated the input as an
INDEX
on the IPs, you could mostly reuse the code from earlier (of course, theunique
part wouldn't be necessary anymore)Demo