1

I'm writing a powershell script to call a RESTful API and I need to parse the response. I'm having trouble parsing the response because there isn't a key name to the array. The API just returns contents of an array:

[
    {
        "ProfileId": "b9b4bf0b-fea3-4464-af91-b79b521d36ba",
        "SourcePhoneNumber": "8880001111",
        "FirstName": "Peter"
    },
    {
        "ProfileId": "b9b4bf1b-cta3-4464-af91-b68c521d36ba",
        "SourcePhoneNumber": "8660001111",
        "FirstName": "Fred"
    }
]

Here's how I'm calling the API and getting the response:

$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
}

The 2nd to last line "Write-Host $json[0]... is where I'm looking to access the ProfileID.

The response is getting written to c:\response2.txt so I know the API request is working and I'm getting good data back from API call.

So what am I doing wrong in accessing the ProfileId of the objects?

2
  • 1
    Your rest method returns a JSON string. Invoke-RestMethod implicitly converts that into usable PowerShell objects. You convert it back to useless JSON text, and then can't use it. Try $response[0] . Commented Feb 21, 2017 at 18:52
  • That was it, you rock! Thanks Commented Feb 21, 2017 at 19:09

1 Answer 1

0

As TessellatingHeckler stated - i just needed to not convert it to json and use $response[0].ProfileId

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.