如何使用PowerShell提取JSON的末级键名及其对应值?
PowerShell提取JSON末级键值对解决方案
问题说明
需要从指定JSON中提取所有末级键名及其对应值,并按对齐格式输出。
原始JSON内容
{ "Data": { "OS_Support": { "SupportedOS": [ "Microsoft Windows 10", "Microsoft Windows 11" ] }, "MinFreeDiskSpace": { "SupportedDisk": 20 }, "MinMemorySize": { "SupportedMemory": 8 }, "App": { "Name": "Notepad", "Version": "1.2.3.4" } } }
期望输出
SupportedOS Microsoft Windows 10, Microsoft Windows 11 SupportedDisk 20 SupportedMemory 8 Name Notepad Version 1.2.3.4
原命令问题
你之前尝试的命令仅能获取Data节点下的一级属性(如OS_Support),无法深入到末级键值:
(Get-Content -Path "JsonPath" | ConvertFrom-Json ).Data | Get-Member | Where-Object { $_.MemberType -match "Property" }
解决方案
方法1:通用递归遍历(适配任意JSON结构)
编写递归函数自动遍历所有层级,筛选出末级键值对并格式化输出:
function Get-LeafProperties { param( [Parameter(ValueFromPipeline)]$InputObject ) process { if ($InputObject -is [PSCustomObject]) { foreach ($prop in $InputObject.PSObject.Properties) { # 如果属性值仍是对象,继续递归遍历 if ($prop.Value -is [PSCustomObject]) { $prop.Value | Get-LeafProperties } else { # 将数组转为逗号分隔的字符串 $value = if ($prop.Value -is [array]) { $prop.Value -join ', ' } else { $prop.Value } [PSCustomObject]@{ Key = $prop.Name Value = $value } } } } } } # 执行提取并格式化输出 $jsonData = Get-Content -Path "JsonPath" | ConvertFrom-Json $jsonData.Data | Get-LeafProperties | Format-Table -AutoSize -HideTableHeaders
方法2:固定结构直接访问(适合已知JSON层级)
如果JSON结构固定,可直接逐层访问末级属性,效率更高:
$json = Get-Content -Path "JsonPath" | ConvertFrom-Json [PSCustomObject]@{ SupportedOS = $json.Data.OS_Support.SupportedOS -join ', ' SupportedDisk = $json.Data.MinFreeDiskSpace.SupportedDisk SupportedMemory = $json.Data.MinMemorySize.SupportedMemory Name = $json.Data.App.Name Version = $json.Data.App.Version } | Format-Table -AutoSize -HideTableHeaders
内容的提问来源于stack exchange,提问作者Dhillli4u
相关产品推荐
相关产品推荐

