Search code examples
powershellhashtablepscustomobject

Converting PSCustomObject to Hashtable


I'm having some problems converting some data from a json payload. The closest I've gotten is converting it to a PSCustomObject like below;

Fields
------
{@{short=true; title=Status; value=Status text.}, @{short=true; title=Type; value=Type text.}, @{short=false; title=Detail; value=This is some example detail text.}}

However I need to convert it to a Hashtable in the following format. Any help would be hugely appreciated.

Name                           Value
----                           -----
short                          true
title                          Status
value                          Status text.
short                          true
title                          Type
value                          Type text.
short                          false
title                          Detail
value                          This is some example detail text.

Thanks,


Solution

  • If we assume your JSON has been converted to object $obj, you can do the following to output an array of hash tables.

    $obj.Fields | Foreach-Object {
        $hash = [ordered]@{}
        $_.PsObject.Properties | Foreach-Object { 
            $hash[$_.Name] = $_.Value
        }
        $hash
    }
    

    Your output will need to be an array of hash tables because a single hash table cannot have duplicate key names.