I am trying to iterate through some JSON when the exact structure is unknown.
This JSON looks like this:
"object" : {
"Item1" : {
"property1" : "a"
"property2" : "b"
}
}
"Item2" : {
"property1" : "c"
"property2" : "d"
}
}
}
The problem is, I don't know what the actual name of Item1 or Item2 is going to be. It is a string of alphanumeric characters that is different on each call.
I have tried
$json_response = $response.object
foreach($item in $json_response) {
$id = $item.property1
Write-Host $id
}
However the $id value never gets set to the value of proprty1. The Write-Host always prints out an empty string.
If I simply do a
Write-Host $json_response
I get something like
@{Item1=; item2=}
I thought this may have been a hash table that would allow me to iterate through it using keys, but there is no Keys property.
Can anyone assist?
Update: Lee_Dailey's response has gotten me further, but still cannot access the properties. With Lee_Dailey's help, I have come up with the following:
foreach ($item in $response_json.PSobject.Properties) {
$json2 = $item | ConvertTo-Json
Write-Host $json2
}
This creates the following JSON
{
"Value": {
"property1": "a",
"property2": "b"
}
}
However I still cannot access property1. Doing
$id = json2.Value.property1
Write-Host $id
results in an empty value. How do I access the properties in the JSON in the $json2 variable?
Update 2. I think I got it working, but I don't know if this is correct or a hack. Updating the code from above to
$json2 = $item | ConvertTo-Json | ConvertFrom-Json
Seems to allow me to do
$id = $json2.Value.property1
I am not sure where "Value" came from. It is not part of the HTTP response. It also seems odd to convert to JSON and then convert it back, however that seems to expose the properties.