提问人:Maxim Suslov 提问时间:11/17/2023 最后编辑:Maxim Suslov 更新时间:11/17/2023 访问量:71
如何按其他数组中的值过滤元素
How to filter elements by values from another arrays
问:
我有以下JSON数据:
{
"services": [
{
"name": "B1",
"criticality": "BC"
},
{
"name": "B2",
"criticality": "BC"
},
{
"name": "M1",
"criticality": "MC"
},
{
"name": "M2",
"criticality": "MC"
},
{
"name": "M3",
"criticality": "MC"
},
{
"name": "M4",
"criticality": "MC"
}
],
"links": [
{
"from_name": "B1",
"to_name": "M1"
},
{
"from_name": "M1",
"to_name": "M2"
},
{
"from_name": "M2",
"to_name": "B2"
},
{
"from_name": "M1",
"to_name": "M3"
},
{
"from_name": "M4",
"to_name": "M2"
}
]
}
我想找到那些拥有并依赖其他服务的服务。criticality==MC
criticality==MC
输出可能如下所示: 服务及其依赖项
{
"M1": [
"M2",
"M3"
],
"M4": [
"M2"
]
}
(它可以是一个数组而不是列表)
怎么做?
当我深入研究链接时,我丢失了有关服务的信息,反之亦然:
.links[] as $in | .services.[] | select(.name == $in.from_name) | select(.criticality == "MC")
将产生:
{
"name": "M1",
"criticality": "MC"
}
{
"name": "M2",
"criticality": "MC"
}
但是没有关于..links
答:
1赞
Maxim Suslov
11/17/2023
#1
我的解决方案是:
# find the MC services and put them into $mc
[ .services[] | select(.criticality == "MC") | .name ] as $mc |
# filter links by having MC only in source and target
[ .links[] | select(.from_name | IN($mc[])) | select(.to_name | IN($mc[])) ] |
# group results by .from_name
group_by(.from_name) | map({(.[0].from_name):map(.to_name)}) | add
评论
criticality=MC
BC
M2
M3