【发布时间】:2017-07-11 13:27:21
【问题描述】:
我正在编写一个 powershell 脚本来调用 RESTful API,我需要解析响应。我无法解析响应,因为数组没有键名。 API 只返回一个数组的内容:
[
{
"ProfileId": "b9b4bf0b-fea3-4464-af91-b79b521d36ba",
"SourcePhoneNumber": "8880001111",
"FirstName": "Peter"
},
{
"ProfileId": "b9b4bf1b-cta3-4464-af91-b68c521d36ba",
"SourcePhoneNumber": "8660001111",
"FirstName": "Fred"
}
]
以下是我调用 API 并获得响应的方式:
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("content-type", "application/json")
$headers.Add("Accept-Language", "en-US")
$headers.Add("Authorization", "OAuth $AccessToken")
$response = Invoke-RestMethod "$($privateApiUrl)/api/v1/profiles" -Headers $headers -Method Get -ErrorVariable RestError -ErrorAction SilentlyContinue
if ($RestError)
{
$HttpStatusCode = $RestError.ErrorRecord.Exception.Response.StatusCode.value__
$HttpStatusDescription = $RestError.ErrorRecord.Exception.Response.StatusDescription
Throw "Http Status Code: $($HttpStatusCode) `nHttp Status Description: $($HttpStatusDescription)"
}
else {
Write-Host $response
#Need to parse the first ProfileId out of the response here
$json = ConvertTo-Json -InputObject @( $response )
Write-Host $json[0].ProfileId #This outputs nothing
$response | Out-File -FilePath c:\response2.txt
}
倒数第二行“Write-Host $json[0]... 是我要访问 ProfileID 的地方。
响应被写入 c:\response2.txt,所以我知道 API 请求正在运行,并且我从 API 调用中获得了良好的数据。
那么我在访问对象的 ProfileId 时做错了什么?
【问题讨论】:
-
你的 rest 方法返回一个 JSON 字符串。 Invoke-RestMethod 将其隐式转换为可用的 PowerShell 对象。您将其转换回无用的 JSON 文本,然后就无法使用它。试试
$response[0]。 -
就是这样,你摇滚!谢谢
标签: json rest powershell powershell-2.0 powershell-4.0