Hashtables from ConvertFrom-json have different type from powershells built-in hashtables, how do I make them the same?

json, powershell

Solution

Here's a quick function to convert a PSObject back into a hashtable (with support for nested objects; intended for use with DSC ConfigurationData, but can be used wherever you need it).

function ConvertPSObjectToHashtable
{
    param (
        [Parameter(ValueFromPipeline)]
        $InputObject
    )

    process
    {
        if ($null -eq $InputObject) { return $null }

        if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string])
        {
            $collection = @(
                foreach ($object in $InputObject) { ConvertPSObjectToHashtable $object }
            )

            Write-Output -NoEnumerate $collection
        }
        elseif ($InputObject -is [psobject])
        {
            $hash = @{}

            foreach ($property in $InputObject.PSObject.Properties)
            {
                $hash[$property.Name] = ConvertPSObjectToHashtable $property.Value
            }

            $hash
        }
        else
        {
            $InputObject
        }
    }
}

Problem

I have a json file (test.json) that looks something like this: ``` { "root": { "key":"value" } } ``` I'm loading it into powershell using something like this: ``` PS > $data = [System.String]::Join("", [System.IO.File]::ReadAllLines("test.json")) | ConvertFrom-Json root ---- @{key=value} ``` I'd like to be able to enumerate the keys of the 'hashtable' like object that is defined by the json file. So, Ideally, I'd like to be able to do something like: ``` $data.root.Keys ``` and get ["key"] back. I can do this with the built-in hashtables in powershell, but doing this with a hashtable loaded from json is less obvious. In troubleshooting this, I've noticed that the fields returned by ConvertFrom-json have different types than those of Powershell's hashtables. For example, calling .GetType() on a built-in hashtable makes shows that it's of type 'Hashtable': ``` PS > $h = @{"a"=1;"b"=2;"c"=3} PS > $h.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Hashtable System.Object ``` doing the same for my json object yields PSCustomObject: ``` PS > $data.root.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False PSCustomObject System.Object ``` Is there any way to cast or transform this object into a typical powershell Hashtable?

Original source

Related problems