问题描述
这是我在PowerShell中编写的GET请求:
$registry = Invoke-WebRequest -Uri "https://${web_ip}/v1/registry/" -Method GET -Headers @{Authorization="token $token"} -ContentType "application/json"
Write-Host $registry
[{“ user”:“ corey”,“ project”:“ 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”,这是我的主要问题。
我坚持这个问题,有什么想法吗?我将不胜感激。
解决方法
响应具有Content属性,其中包含原始JSON。使用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