如何从HtmlWebResponseObject解析JSON

问题描述

这是我在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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...