首页 > 解决方案 > 循环遍历 Powershell 中没有键/值对而是值列表的转换后的 json 数据?

问题描述

JSON:

[
  {
    "Category-1": [
      "Value1"
    ]
  },
  {
    "Category-2": [
      "Value1"
    ]
  },
  {
    "Category-3": [
      "Value1",
      "Value2"
    ]
  }
]

PowerShell 脚本:

$jsonToParse = (Get-Content -Path $jsonPath) -join "`n" | ConvertFrom-Json

foreach ($entry in $jsonToParse) {
     log -Message ($entry) #Log function spits output to file
}

输出:

[10:39:03]@{Category-1=System.Object[]}
[10:39:03]@{Category-2=System.Object[]}
[10:39:03]@{Category-3-Med=System.Object[]}

我该如何解析这个?我有方括号和大括号,我很难找到一个立足点来真正获取数据。

我该怎么做才能获得“类别”名称?我该怎么做才能获得每个类别名称的“值”?我认为,这些并非所有键/值对的事实是给我带来麻烦的原因。

标签: jsonpowershellloops

解决方案


我认为你所追求的是这样的:

# use the -Raw switch to get the file content as one single string
$jsonToParse = Get-Content -Path $jsonPath -Raw | ConvertFrom-Json

foreach ($entry in $jsonToParse) {
    # format a string for the log file using the object ($entry) Name followed by the Value
    # This Value can be an array of more than one items, so join these with a comma
    $msg = '{0} = {1}' -f $entry.PSObject.Properties.Name, ($entry.PSObject.Properties.Value -join ', ')
    log -Message $msg  #Log function spits output to file
}

输出:

[10:39:03]Category-1 = Value1
[10:39:03]Category-2 = Value1
[10:39:03]Category-3 = Value1, Value2

推荐阅读