我正在编写一个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时我做错了什么?
答案 0 :(得分:0)
正如TessellatingHeckler所说 - 我只是不需要将它转换为json并使用$ response [0] .ProfileId