Forum Discussion
Powershell JSON
I am pulling back some JSON formatted data via Invoke-RestMethod.
I am trying to figure out how to get that data into usable format so that I can use the returned data in If else statements further down in the script I am using. The data is formatted such as when I use the following commands.
$searchResultsResponse = Invoke-RestMethod -Method POST -Uri $searchUri -ContentType application/json -Header $requestHeader -Body $searchResultsRequest
$searchResultsResponse.businessObjects.fields
DisplayName Value
Incident 1
Location NC
Status 4
Incident 2
Location NC
Status 2
3 Replies
- gerald_doeserichCopper Contributor
Without seeing the actual JSON layout and what you want to use in the If clause we can't really help you.
But Invoke-RestMethod should automatically convert any JSON to a PSCustomObject which you should be able to use in any If/Else clause.- Ronald LawrimoreCopper Contributor
- gerald_doeserichCopper Contributor
I don't think there is a direct way of parsing the inner fields to a PSCustomObject.
The following should do the trick and give you a PSCustomObject to work with:
# $JSON is the result from your Invoke-WebRequest ForEach($entry in $JSON) { $newFields = @() $rawFields = $entry.Fields ForEach($rawField in $rawFields) { $parameters = [PSCustomObject]@{} # Remove first 2 letters (as they are '@{') and the last '}' $rawField = $rawField.Substring(2, $rawField.Length - 4) # Parameters seem to be splitted by a ';' $rawParameters = $rawField -split ';' ForEach($pair in $rawParameters) { # Key = Value $split = $pair -split '=' # Trim the start as after the ';' a space occurs $name = $split[0].TrimStart() # Skip empty pairs If([String]::IsNullOrEmpty($name)) { Continue } $parameters | Add-Member -NotePropertyName $name -NotePropertyValue $split[1] } $newFields += $parameters } # Override original Fields entry $entry.Fields = $newFields }