PowerShell用C风格循环遍历JSON嵌套数组匹配告警ID合并数据
PowerShell 嵌套JSON数组合并与字段提取实现
需求说明
我们需要合并两份JSON数据,按告警ID(AlertID)匹配后提取指定字段生成目标结构,同时遍历输出entities数组中的所有非空值。要求全部使用C风格for循环处理数组,避免重复嵌套循环提升执行效率。
目标结构字段:
- AlertID:来自任意一份匹配的JSON即可
- Tags:来自JSON1的对应字段
- IncidentName:来自JSON2的事件名称
- IncidentID:来自JSON2的事件ID
- entities:来自JSON2的告警实体数组
- devices:来自JSON2的告警设备数组
实现步骤
1. 读取并解析JSON文件
首先将两份JSON内容加载为PowerShell可操作的自定义对象:
# 读取JSON文件并转换为对象 $json1 = Get-Content "json1.json" -Raw | ConvertFrom-Json $json2 = Get-Content "json2.json" -Raw | ConvertFrom-Json
2. 预构建AlertID索引映射(避免重复循环)
只遍历一次JSON1的所有AlertID,构建哈希表作为索引,后续匹配直接O(1)查找,无需每次全量扫描JSON1:
$alertTagMap = @{} # 外层C风格for循环遍历JSON1所有事件 for ($i = 0; $i -lt $json1.Count; $i++) { $currentIncident = $json1[$i] $tags = $currentIncident.tags # 内层循环遍历当前事件下的所有AlertID for ($j = 0; $j -lt $currentIncident.AlertId.Count; $j++) { $alertId = $currentIncident.AlertId[$j] # 存入哈希表,键为AlertID,值为对应tags $alertTagMap[$alertId] = $tags } }
3. 遍历JSON2嵌套结构生成目标数据
全部使用C风格for循环处理多层嵌套数组,匹配AlertID后生成目标对象,同时提取entities非空值:
# 定义结果数组 $mergeResult = @() # 遍历JSON2根节点下的value数组(所有事件) for ($m = 0; $m -lt $json2.value.Count; $m++) { $incident = $json2.value[$m] $incidentName = $incident.incidentName $incidentId = $incident.incidentId.ToString() # 统一为字符串类型和JSON1匹配 # 遍历当前事件下的所有告警 for ($n = 0; $n -lt $incident.alerts.Count; $n++) { $alert = $incident.alerts[$n] $alertId = $alert.alertId # 检查当前告警ID是否在预构建的映射表中存在 if ($alertTagMap.ContainsKey($alertId)) { # 构建目标对象 $targetObj = [PSCustomObject]@{ AlertID = $alertId Tags = $alertTagMap[$alertId] IncidentName = $incidentName IncidentID = $incidentId entities = $alert.entities devices = $alert.devices } $mergeResult += $targetObj # 遍历entities输出所有非空值 Write-Host "`n=== AlertID $alertId 非空实体属性 ===" for ($p = 0; $p -lt $alert.entities.Count; $p++) { $entity = $alert.entities[$p] # 遍历实体所有属性 $entityProps = $entity.PSObject.Properties for ($q = 0; $q -lt $entityProps.Count; $q++) { $prop = $entityProps[$q] $propValue = $prop.Value # 仅输出非空属性 if ($null -ne $propValue -and $propValue -ne '') { Write-Host "$($prop.Name): $propValue" } } } } } } # 输出合并后的完整结果 Write-Host "`n=== 合并后的完整结果 ===" $mergeResult | ConvertTo-Json -Depth 10
核心优化点
- 预构建AlertID哈希映射:将原本需要嵌套循环匹配的O(n*m)时间复杂度降至O(n+m),避免上层循环每次重复扫描JSON1
- 全C风格for循环处理数组:相比foreach循环可以精准控制迭代过程,避免隐式迭代产生的额外开销,更适合深度嵌套数组的场景
- 深度控制:转换JSON结果时指定
-Depth 10参数,避免PowerShell默认深度限制导致嵌套对象被截断
内容的提问来源于stack exchange,提问作者aster007
相关产品推荐
相关产品推荐

