'How to parse RESTful API response with powershell that doesn't have key defined of the array

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1252399