我正在编写一个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时做错了什么呢?
1条答案
按热度按时间n53p2ov01#
正如TessellatingHeckler所述-我只需要不将其转换为json,而使用$response[0].ProfileId