Home > Net >  ConvertTo-JSON from string - access JSON fields by name in PowerShell
ConvertTo-JSON from string - access JSON fields by name in PowerShell

Time:10-12

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=

CodePudding user response:

  • 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'
  • Related