Reputation: 18177
How can I access a field like $body.uuid? This is what I have tried:
$body = @"
{ "uuid": "Test07",
"subject": "Template07-Subject",
}
"@
$bodyJSON = ConvertTo-Json $body
Write-Host $bodyJSON
Write-Host "uuid=$($bodyJSON.uuid)"
Write-Host "uuid=$($bodyJSON.$uuid)"
Results:
"{ \"uuid\": \"Test07\",\r\n \"subject\": \"Template07-Subject\",\r\n}"
uuid=
uuid=
Upvotes: 1
Views: 2865
Reputation: 437109
Your $body
variable contains a JSON string.
ConvertTo-Json
on it - the latter's purpose is to convert objects to JSON strings.In order to parse the JSON string into an object (graph), pass it to ConvertFrom-Json
, which returns [pscustomobject]
instance(s).
.uuid
on the resulting object(s).Note:
As bluuf points out, your original JSON contains an extraneous ,
after the "subject"
property, which makes it technically malformed - this has been corrected below.
Note, however, that ConvertTo-Json
in PowerShell (Core) 7+ still accepts such JSON, whereas Windows PowerShell does not.
# Create a string containing JSON
$body = @"
{
"uuid": "Test07",
"subject": "Template07-Subject"
}
"@
# Parse the JSON string into a PowerShell object (graph).
$bodyAsObject = ConvertFrom-Json $body
# Now you can use property access.
$bodyAsObject.uuid # -> 'Test07'
Upvotes: 3