Home > Mobile >  Issue with API result not converting to object in powershell
Issue with API result not converting to object in powershell

Time:01-27

I have an odd problem. I'm getting some data back from an API and storing it in $response

The result looks like this (I've changed the names and IDs):

accountId           : 1234
secureScoreProgress : @{startDate=2022-12-12 00:00:00.000; endDate=2023-01-26 00:00:00.000; totalDays=2738; minScore=76; maxScore=534.18; averageScore=257.33; data=System.Object[]}
monitoredAccounts   : @{total=479; data=System.Object[]}
accountIdToNameMap  : @{1234=Apple; 5432=Microsoft; 2584=Tesla; 7533=Ben and Jerry; 7534=Micool Paul Inc; 7549=AGLX; 7558=Samsung}

I'm interested in the 'accountIdToNameMap' section, so I store it to an object like so:

$accounts = $response.accountIdToNameMap

This returns the following list:

1234 : Apple
5432 : Microsoft
2584 : Tesla
7533 : Ben and Jerry
7534 : Micool Paul Inc
7549 : AGLX
7558 : Samsung

If I try to do a foreach on the list, it only loops once and outputs that whole list in one go.

I've tried to ConvertFrom-JSON but that throws Invalid JSON primitive: .

I've tried to ConvertTo-JSON, which works, but I still can't loop through the results. After ConvertTo-JSON, the result looks like this:

{
    "1234":  "Apple",
    "5432":  "Microsoft",
    "2584":  "CH Hausmann",
    "7533":  "Hughes Fowler Carruthers",
    "7534":  "Tempest Resourcing",
    "7549":  "Cream UK Ltd",
    "7558":  "Illuminatis / Scout Data"
}

What am I doing wrong?

CodePudding user response:

If I try to do a foreach on the list

It's not a list, it's an object. You can enumerate its properties by accessing the hidden psobject member:

foreach ($property in $accounts.psobject.Properties) {
    "The `$accounts object has a property named '$($property.Name)' with value '$($property.Value)'"
}

You can use this to build a hashtable (an unordered dictionary):

$idToNameMap = @{}
foreach ($property in $accounts.psobject.Properties) {
    $idToNameMap[$property.Name] = $property.Value
}

Now you can easily use it as a lookup table:

$idToNameMap['1234'] # resolves to "Apple"
  • Related