PowerShell遍历嵌套JSON提取entitySnapshot_properties属性问题求助
问题根因
- ConvertFrom-Json默认最大解析深度为2,你代码中
-Depth 99参数被注释,导致深层嵌套的JSON结构被截断,无法识别深层的snapshot_groupSnapshotChildren节点 - 现有脚本仅遍历根节点属性,未实现递归遍历,无法适配动态节点名和不确定的嵌套深度
完整实现代码
# 初始化结果数组 $extractedResults = @() # 定义递归遍历函数 function Traverse-JsonNode { param( [Parameter(Mandatory=$true)] $InputNode ) # 检查当前节点是否存在entitySnapshot_properties if ($InputNode.PSObject.Properties.Name -contains "entitySnapshot_properties") { $props = $InputNode.entitySnapshot_properties # 构造当前节点的结果对象 $currentResult = [PSCustomObject]@{ nodeName = $props._name # 按需提取字段,不存在则留空 _class = $props._class ?? $null _ownerID = $props._ownerID ?? $null monitor_snapshot_hostName = $InputNode.monitor_snapshot_hostName ?? $null } $script:extractedResults += $currentResult } # 递归遍历子分组节点 if ($InputNode.PSObject.Properties.Name -contains "snapshot_groupSnapshotChildren") { foreach ($childGroup in $InputNode.snapshot_groupSnapshotChildren.PSObject.Properties) { Traverse-JsonNode -InputNode $childGroup.Value } } # 递归遍历监控节点(Heartbeat等节点在此路径下) if ($InputNode.PSObject.Properties.Name -contains "snapshot_monitorSnapshotChildren") { foreach ($childMonitor in $InputNode.snapshot_monitorSnapshotChildren.PSObject.Properties) { Traverse-JsonNode -InputNode $childMonitor.Value } } } # 主逻辑 $info = Get-Content -Path .\input.json -Raw if (-not $info) { Write-Host "Unhandled Exception parsing data for $sitescopeFQDNhost`nExit Script" -ForegroundColor Red -BackgroundColor Black exit 1 } # 开启足够的解析深度 $ResJsonObj = $info | ConvertFrom-Json -Depth 99 # 从根节点开始遍历 Traverse-JsonNode -InputNode $ResJsonObj # 输出结果,可根据需求改为Export-Csv等导出操作 $extractedResults | Format-List
结果说明
运行后会输出所有节点的指定字段,你可以根据需要筛选对应节点的属性:
- Test节点可直接取
_name、_class字段 - Guacamole节点可直接取
_name、_ownerID字段 - Heartbeat on Guacamole节点可直接取
_name、monitor_snapshot_hostName字段
内容的提问来源于stack exchange,提问作者user17206036
相关产品推荐
相关产品推荐

