curtcab
curtcab

Reputation: 81

Parsing JSON array with PowerShell

I'm having issues returning specific data from an API query with PowerShell. I'm making a simple API call to grab a user which works great.

$Response = Invoke-RestMethod -uri $uri -Method GET -Headers $Headers
$Response

The call returns the following.

Total Sum   Users         Groups
----- ----- -----         ------
    1     1 @{123456789=} @{Test Users=System.Object[]; Global Users=System.Object[]...

$Response.Users returns the following

123456789
---------
@{name= Test Case; fullname=Test Tester Case; office=Area 51;....

The issue is the number "123456789" is a unique identifier that changes with every user. In order to pull the needed data from each user I need to be able to parse and grab just that number.

Here is the JSON output from $Response.Users

{
    "123456789": {
      "name": "Test Case",
      "fullname": "Tester Test Case",
      "office": "Area 51",
      "country": "United States",
      "groups": [
        "Test Users",
        "Global Users",
        "Test OU"     
      ]
    }
}

Any help is greatly appreciated!

Thanks

Upvotes: 5

Views: 4653

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59031

You can access the name of the note property using the default powershell property PsObject and retrieve the name of it:

$json = 
@'
{
    "123456789": {
      "name": "Test Case",
      "fullname": "Tester Test Case",
      "office": "Area 51",
      "country": "United States",
      "groups": [
        "Test Users",
        "Global Users",
        "Test OU"     
      ]
    }
}
'@


$json | ConvertFrom-Json | ForEach-Object {$_.PsObject.Properties.Name}

Or in your case:

$Response.Users | ConvertFrom-Json | ForEach-Object {$_.PsObject.Properties.Name}

Should do the trick ;-)

Upvotes: 5

Related Questions