1

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=
2
  • 1
    The string already contains json - you want $object = ConvertFrom-Json $body; $object.uuid Commented Oct 8, 2021 at 21:19
  • @MathiasR.Jessen I tried ConverFrom-JSON and it gave: ConvertFrom-Json : Invalid JSON primitive: Commented Oct 8, 2021 at 21:45

1 Answer 1

3
  • Your $body variable contains a JSON string.

    • Unless your intent is to embed that string in another JSON string, do not call 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).

    • You can use regular property access, such as .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'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the good explanation. The comma was there because I delete a bunch of other fields to create a smaller test case, and forgot about it. I didn't catch that was the reason for the error with ConvertFrom-Json. So bottom line, PowerShell doesn't have a JSON object concept then. Instead it uses pscustomobject to simulate that?
@NealWalters, yes, it's easy to forget a trailing comma, which is why some JSON parsers conveniently ignore it. To PowerShell, JSON is just a string - a text-based serialization format that must be deserialized into a language-specific object graph (including in JavaScript with JSON.parse()). In PowerShell, you use ConvertFrom-Json, which returns an [array of] [nested] [pscustomobject] instance(s).

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.