36

I want to get a JSON representation of a Hashtable such as this:

@{Path="C:\temp"; Filter="*.js"}

ConvertTo-Json results in:

{
    "Path":  "C:\\temp",
    "Filter":  "*.js"
}

However, if you convert that JSON string back with ConvertFrom-Json you don't get a HashTable but a PSCustomObject.

So how can one reliably serialize the above Hashmap?

abatishchev
  • 95,331
  • 80
  • 293
  • 426
Marc
  • 11,311
  • 11
  • 60
  • 73
  • Possible duplicate of [PSCustomObject to Hashtable](http://stackoverflow.com/questions/3740128/pscustomobject-to-hashtable) – Martin Brandl Nov 08 '16 at 20:58

6 Answers6

51
$json = @{Path="C:\temp"; Filter="*.js"} | ConvertTo-Json

$hashtable = @{}

(ConvertFrom-Json $json).psobject.properties | Foreach { $hashtable[$_.Name] = $_.Value }

Adapted from PSCustomObject to Hashtable

Community
  • 1
  • 1
sodawillow
  • 11,431
  • 4
  • 34
  • 43
16

A little late to the discussion here, but in PowerShell 6 (Core) there is a -AsHashtable parameter in ConvertFrom-Json.

ThePoShWolf
  • 171
  • 1
  • 3
13

JavaScriptSerializer is available since .NET3.5 (may be installed on XP, included in Win7 and newer), it's several times faster than Convert-FromJSON and it properly parses nested objects, arrays etc.

function Parse-JsonFile([string]$file) {
    $text = [IO.File]::ReadAllText($file)
    $parser = New-Object Web.Script.Serialization.JavaScriptSerializer
    $parser.MaxJsonLength = $text.length
    Write-Output -NoEnumerate $parser.DeserializeObject($text)
}
wOxxOm
  • 53,493
  • 8
  • 111
  • 119
  • 3
    In PowerShell 5.1 I found that `$parser.DeserializeObject($text)` deserialized to a .NET Dictionary, not a Hashtable However, the Deserialize method, as opposed to the DeserializeObject method, does deserialize to a Hashtable: `$parser.Deserialize($text, @{}.GetType())` . – Simon Tewsi Jan 03 '18 at 09:49
  • 2
    @SimonTewsi You can use `[hashtable]` instead of `@{}.GetType()`. – beatcracker Sep 18 '19 at 15:07
5

The answer for this post is a great start, but is a bit naive when you start getting more complex json representations.

The code below will parse nested json arrays and json objects.

[CmdletBinding]
function Get-FromJson
{
    param(
        [Parameter(Mandatory=$true, Position=1)]
        [string]$Path
    )

    function Get-Value {
        param( $value )

        $result = $null
        if ( $value -is [System.Management.Automation.PSCustomObject] )
        {
            Write-Verbose "Get-Value: value is PSCustomObject"
            $result = @{}
            $value.psobject.properties | ForEach-Object { 
                $result[$_.Name] = Get-Value -value $_.Value 
            }
        }
        elseif ($value -is [System.Object[]])
        {
            $list = New-Object System.Collections.ArrayList
            Write-Verbose "Get-Value: value is Array"
            $value | ForEach-Object {
                $list.Add((Get-Value -value $_)) | Out-Null
            }
            $result = $list
        }
        else
        {
            Write-Verbose "Get-Value: value is type: $($value.GetType())"
            $result = $value
        }
        return $result
    }


    if (Test-Path $Path)
    {
        $json = Get-Content $Path -Raw
    }
    else
    {
        $json = '{}'
    }

    $hashtable = Get-Value -value (ConvertFrom-Json $json)

    return $hashtable
}
Esten Rye
  • 51
  • 1
  • 1
4

I believe the solution presented in Converting JSON to a hashtable is closer to the PowerShell 6.0 implementation of ConvertFrom-Json

I tried with several JSON sources and I always got the right hashtable.

$mappings = @{
  Letters = (   
      "A",
      "B")
  Numbers        = (
      "1",
      "2",
      "3")
  Yes = 1
  False = "0"
}

# TO JSON 
$jsonMappings = $mappings  | ConvertTo-JSON
$jsonMappings

# Back to hashtable 
# In PowerShell 6.0 would be:
#   | ConvertFrom-Json -AsHashtable
$jsonMappings | ConvertFrom-Json -As hashtable
Gonzalo Contento
  • 817
  • 9
  • 21
-2

you can write a function convert psobject to hashtable.

I wrote a answer here:enter link description here

Hu Xinlong
  • 27
  • 4