1

这是我在 PowerShell 中编写的 GET 请求:

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

它将显示如下内容:

[{“用户”:“corey”,“项目”:“corey”,“registry”:“corey-registry”}]

我试图解析响应以从键“注册表”中获取值,但它没有按我的预期工作。

# 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

我不知道如何转换HtmlWebResponseObject为 json 或列表对象,我也不知道如何在代码中获取值“corey-registry”,这是我的主要问题。

我卡在这个问题上,有什么想法吗?我将不胜感激任何帮助。

4

1 回答 1

1

响应具有包含原始 JSON的Content属性。使用ConvertFrom-Json将其转换为对象。然后,您可以轻松访问该registry属性。

这是一个带有一些解释的(非常冗长的)示例:

# 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
于 2020-09-29T09:27:59.273 回答