2017-02-21 5 views
1

私はRESTfulなAPIを呼び出すためにpowershellスクリプトを書いていますが、レスポンスを解析する必要があります。配列にキー名がないので、応答の解析に問題があります。 APIは、単に配列の内容を返します。配列のキーが定義されていないpowershellでRESTfulな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 
} 

第二は、最後の行、「書き込みホストの$ JSONに[0] ... ProfileIDにアクセスするための場所です。

応答がc:\ response2.txtに書き込まれているので、APIリクエストが機能していて、API呼び出しから良好なデータが返ってきています。

だから私はオブジェクトのProfileIdにアクセスする際に間違っているのですか?

+1

を.ProfileId。 Invoke-RestMethodはそれを暗黙的に使用可能なPowerShellオブジェクトに変換します。無用なJSONテキストに変換して使用することはできません。 '$ response [0]'を試してください。 – TessellatingHeckler

+0

それは、あなただった!ありがとう – user1252399

答えて

0

TessellatingHecklerが述べたように - 私はJSONと使用$応答にそれを変換しないために必要な[0]あなたの残りのメソッドは、JSON文字列を返します

関連する問題