【问题标题】:How to iterate json object in powershell如何在powershell中迭代json对象
【发布时间】:2022-01-23 10:49:49
【问题描述】:

我正在使用以下代码在 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. 如果条件不往里面走

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    它不起作用,因为变量 awsFileResponse 不是 Json 对象而是字符串。因此,首先您必须将字符串解析为自定义对象。然后你必须循环它里面的所有属性。并检查 $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
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 2019-07-21
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多