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.
- it is not printing anything for the below lines Write-Host $KeyParam Write-Host $KeyParam.NAME Write-Host $KeyParam.VALUE
- it is not going to the inside if the condition
CodePudding user response:
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
}
}