How to parse JSON from HtmlWebResponseObject

1.3k views Asked by At

Here is the GET request I wrote in PowerShell:

$registry = Invoke-WebRequest -Uri "https://${web_ip}/v1/registry/" -Method GET -Headers @{Authorization="token $token"} -ContentType "application/json"
Write-Host $registry

It will show something like this:

[{"user": "corey", "project": "corey", "registry": "corey-registry"}]

I tried to parse the response to get the value from the key "registry", but it didn't work as my expectation.

# to get the first value in the list
$registry[0] => the output is the same as listed above

# check the type
$registry.GetType() => Microsoft.PowerShell.Commands.HtmlWebResponseObject

I don't know how to convert HtmlWebResponseObject to a json or list object, and I have no idea how to get the value "corey-registry" in code either, that's my main problem.

I stuck at this issue, any ideas? I would appreciate any help.

1

There are 1 answers

0
marsze On BEST ANSWER

The response has the Content property which contains the raw JSON. Use ConvertFrom-Json to convert it into an object. You can then easily access the registry property.

Here is a (quite verbose) example with some explanations:

# get response
$response = Invoke-WebRequest -Uri "https://${web_ip}/v1/registry/" -Method GET -Headers @{Authorization="token $token"} -ContentType "application/json"
# get raw JSON
$json = $response.Content
# deserialize to object
$obj = ConvertFrom-Json $json
# you can now easily access the properties
$registry = $obj.registry