Tuesday, June 8, 2021

Working with JSON in Powershell - Collection of hashtables

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" ] }

Of course we could say that the author of the rest api should change the returned result to make it easier to interact with, but that is not always within our control.

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

The output from that is:
firstItem one two next yes no maybe 6739 red blue green
It is a nice little snippet that gets the job done.

No comments:

Post a Comment

The 2024 State of DevOps Report and the Importance of Internal Development Platforms

On the State of DevOps Report The State of DevOps Report, published annually by the DevOps Research and Assessment (DORA) team, has been a c...