You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无Schema知识时迭代JSON属性与PSCustomObject的通用方法问询

通用解析嵌套JSON属性的方法需求

我需要在不预先了解JSON文件Schema的情况下,迭代其中所有属性和值。现有代码能处理多数测试过的JSON文件或下载内容,但在处理嵌套值时遇到困难。我试过用Get-Member、.psobject.name及NoteProperty相关方法,但这些似乎都需要预先知晓JSON内容结构。

测试用JSON示例

{"FoodChoices": [{"id": 1,"name": "TakeOut","variableGroups": [],"variables": {"Location": {"value": "Fast Food"},"Beverage": {"value": "Soda or Lemondade"},"Tip": {"value": "No Way"}}},{"id": 2,"name": "Gourmet","variableGroups": [],"variables": {"Location": {"value": "Nice Resturant"},"Beverage": {"value": "Dirty Martini"},"Tip": {"value": "Maybe"}}}]}

现有临时迭代代码

$jfile = "$PSScriptRoot\FoodChoice.json"

$file = Get-Content $jFile -Raw
$parse = ($file.substring(0,1) -ne "[")
$json = $file | ConvertFrom-Json

$parent = $json | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
if ($parse -eq $true)
{
   foreach ($p in $parent)
   {
      $d = $json.$p
      if ($d.length -gt 1) { $data = $d }
   }
}
else {$data = $json }
$out = "Key" + "`t" + "Value" + "`n"
$keys = $data | get-member -type properties | Foreach-Object name
foreach ($d in $data)
{
   foreach ($k in $keys)
   {
       $name = $d.$k
       if ($name -match "@")
       {
           $out += "$k`t`n"
           $members = Get-Member -InputObject $name
           foreach ($m in $members)
           {
              if ($m -match "System.Management.Automation.PSCustomObject")
              {
                 $m1 = $m.ToString()
                 $m1 = $m1.Replace("System.Management.Automation.PSCustomObject"," ") 
                 if ($m1 -match "@")
                 {
                    $m1 = $m1.Replace("@{"," ")
                    $m1 = $m1.Replace("}"," ")
                    $m1 = $m1 -split "="
                    $m2 = $m1[0]
                    $m3 = $m1[2]
                    $out += "$m2`t$m3`n"
                 }
                 else {$out += "$name`t$m1`n"}
              }
           }
       }
       else {$out += "$k`t$name`n"}
   }
}
$out
Exit

现有代码输出

Key Value
id  1
name    TakeOut
variableGroups  
variables   
 Beverage   Soda or Lemondade
 Location   Fast Food
 Tip    No Way
id  2
name    Gourmet
variableGroups  
variables   
 Beverage   Dirty Martini
 Location   Nice Resturant
 Tip    Maybe

希望找到一种通用方法,解析类型为System.Management.Automation.PSCustomObject的嵌套属性。

内容的提问来源于stack exchange,提问作者Stan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:13:14