Some time you interact with a rest API, which returns a block of json containing a collection of items that you want to enumerate over. If the collection of items is not in an array, but looks like the following, it is challenging to iterate over the collection.
{ "firstItem" : [ "one", "two" ], "next" : [ "yes", "no", "maybe" ], "6739" : [ "red", "blue", "green" ] }
In PowerShell we can make this collection enumerable with a few extra lines of code.
If you are working with a newer version of PowerShell (version 6 or newer) you can use the -AsHashtable parameter to ConvertFrom-JSON.
If that is not the case, you can still make the json response enumerable as shown below.
$json = ... response from the api $data = $json | ConvertFrom-Json $enumerableData = $data.psobject.properties | Select-Object Name, Value foreach ($element in $enumerableData) { Write-host "$($element.Name)" foreach ($element in $element.Value) { Write-Host "`t$element" } }
It is a nice little snippet that gets the job done.firstItem one two next yes no maybe 6739 red blue green


