如何在 powershell 中迭代 json 对象

How to iterate json object in powershell

我正在使用以下代码在 PowerShell 中迭代 JSON 对象

    $awsFileResponse = '{
   "commitId":"opb274750f582ik",
   "blobId":"io6956a1a967243514e194lk54b86",
   "filePath":"PowershellScript.ps1",
   "fileMode":"NORMAL",
   "fileSize":5755,
   "fileContent":"7"
}'
foreach($KeyParam in $awsFileResponse)
{
    Write-Host 'Ashish'
    Write-Host $KeyParam
    Write-Host $KeyParam.NAME
    Write-Host $KeyParam.VALUE
    if($KeyParam.NAME -eq 'fileContent')
    {
        $fileContentResponse = $KeyParam.VALUE
        Write-Host $fileContentResponse
    }

}

我没有得到我正在寻找的确切输出。

  1. 它没有为以下行打印任何内容 写入主机 $KeyParam 写主机 $KeyParam.NAME 写主机 $KeyParam.VALUE
  2. 如果条件
  3. 是不会往里面走的

它不起作用,因为变量 awsFileResponse 不是 Json 对象而是字符串。所以首先你必须将字符串解析为 Custom Object 。然后你必须循环其中的所有属性。并检查 $keeyParam.NAME 而不是 $keyParam 对象的 fileContent 键条件。

工作代码

   $awsFileResponse = '{
   "commitId":"7cf4ca8ea129c2b9b274750f58245605e081580e",
   "blobId":"1d46ec453a6956a1a967243514e1944754c54b86",
   "filePath":"PowershellScript.ps1",
   "fileMode":"NORMAL",
   "fileSize":5755,
   "fileContent":"7"
}'

#Parse to Json Object 
$jsonObject = $awsFileResponse | ConvertFrom-Json;

#loop all custom object properties
foreach($KeyParam in $jsonObject.psobject.properties)
{
    Write-Host 'Ashish'
    Write-Host $KeyParam
    Write-Host $KeyParam.NAME
    Write-Host $KeyParam.VALUE
    if($KeyParam.NAME -eq 'fileContent')
    {
        $fileContentResponse = $KeyParam.VALUE
        Write-Host $fileContentResponse
    }

}