0

I am iterating JSON object in PowerShell using below code

    $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
    }

}

I am not getting the exact output that I am looking for.

  1. it is not printing anything for the below lines Write-Host $KeyParam Write-Host $KeyParam.NAME Write-Host $KeyParam.VALUE
  2. it is not going to the inside if the condition

1 Answer 1

1

It is not working as the variable awsFileResponse is not a Json Object but a string. So first you have to parse the string to a Custom Object . Then you have to loop all the properties inside it. And check the $keeyParam.NAME instead of $keyParam object for the fileContent key condition.

Working code

   $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
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.