PowerShell用C风格for循环匹配AlertID合并两个JSON的多维哈希表数组数据
PowerShell 按AlertID匹配合并JSON实现(C风格for循环版)
实现规则匹配说明
- 完全使用C风格索引
for循环实现,无嵌套foreach逻辑 - AlertID匹配成功后字段来源严格符合要求:
- AlertID 取自匹配的告警ID
- Tags 来源于JSON1
- IncidentName、IncidentID 来源于JSON2
完整代码
# 1. 读取并解析两个JSON文件,可根据实际存储路径修改 $json1 = Get-Content "json1.json" -Raw | ConvertFrom-Json $json2 = Get-Content "json2.json" -Raw | ConvertFrom-Json $json2IncidentList = $json2.value # 2. 初始化结果数组与AlertID映射表 $resultArray = @() $alertToIncidentMap = @{} # 3. 遍历JSON2构造AlertID到事件信息的映射,全使用C风格for循环 for ($i = 0; $i -lt $json2IncidentList.Count; $i++) { $incidentItem = $json2IncidentList[$i] $alertList = $incidentItem.alerts for ($j = 0; $j -lt $alertList.Count; $j++) { $alertItem = $alertList[$j] $alertToIncidentMap[$alertItem.alertId] = @{ IncidentID = $incidentItem.incidentId IncidentName = $incidentItem.incidentName } } } # 4. 遍历JSON1匹配AlertID生成结果 for ($m = 0; $m -lt $json1.Count; $m++) { $json1Item = $json1[$m] $json1AlertList = $json1Item.AlertId for ($n = 0; $n -lt $json1AlertList.Count; $n++) { $currentAlertId = $json1AlertList[$n] if ($alertToIncidentMap.ContainsKey($currentAlertId)) { # 构造符合要求的结果项 $resultItem = @{} $resultItem.AlertID = $currentAlertId $resultItem.Tags = $json1Item.tags $resultItem.IncidentID = $alertToIncidentMap[$currentAlertId].IncidentID $resultItem.IncidentName = $alertToIncidentMap[$currentAlertId].IncidentName $resultArray += $resultItem } } } # 输出结果验证,可根据需要调整输出格式 $resultArray | ConvertTo-Json
额外说明
- 提前构造映射表的逻辑避免了重复遍历数据,执行效率优于嵌套循环遍历匹配的方案
- 处理AlertID匹配时自动跳过JSON2中不存在对应告警的条目,避免生成无效数据
内容的提问来源于stack exchange,提问作者aster007
相关产品推荐
相关产品推荐

