如何从调用Invoke-WebRequest访问JSON?

Whi*_*uit 2 powershell json curl

我需要调用API(从我的DNS提供程序获取记录列表),这可以使用curl完成.这将返回带有我所有记录的格式化的json

curl -H 'Authorization: Bearer mytoken' -H 'Accept: application/json' https://api.dnsimple.com/v2/12345/zones/example.com/records
Run Code Online (Sandbox Code Playgroud)

但是,我需要能够从PowerShell执行此操作

$uri = "https://api.dnsimple.com/v2/12345/zones/example.com/records"
$headers = @{}
$headers["Authorization"] = "Bearer mytoken"
$headers["Accept"] = "application/json"
$foo = Invoke-WebRequest $uri -Headers $headers 
Run Code Online (Sandbox Code Playgroud)

这个命令运行,但在$ foo中我可以访问返回的JSON吗?

bri*_*ist 8

使用Invoke-WebRequest,您将访问Content属性:$foo.Content

请注意,您也可以使用Invoke-RestMethod,它会自动将JSON响应转换为PowerShell对象.

所以这:

$o = Invoke-RestMethod #params
Run Code Online (Sandbox Code Playgroud)

会是这样的:

$foo = Invoke-WebRequest #params
$o = $foo.Content | ConvertFrom-Json
Run Code Online (Sandbox Code Playgroud)