2017-02-21 21 views
1

我正在寫一個PowerShell腳本調用一個RESTful API,我需要解析響應的定義鍵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 
} 

第2至最後一行的「寫主機$ JSON [0] ......正是我期待訪問簡檔

的響應越來越寫入到C:\ response2.txt所以我知道API請求的工作,我從API調用獲得良好的數據備份。

那麼我在訪問對象的ProfileId時做錯了什麼?

+1

你的休息方法返回一個JSON字符串。 Invoke-RestMethod將其隱式轉換爲可用的PowerShell對象。您將其轉換回無用的JSON文本,然後無法使用它。試試'$ response [0]'。 – TessellatingHeckler

+0

就是這樣,你搖滾!謝謝 – user1252399

回答

0

由於TessellatingHeckler說 - 我只是需要把它轉換成JSON和使用$回覆[0] .ProfileId