Create Hashtable from JSON

I want to get a JSON representation of a Hashtable, for example:

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

ConvertTo-Json results in:

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

However, if you convert this JSON string using ConvertFrom-Json , you will not get a HashTable, but a PSCustomObject.

So how can you reliably serialize the above Hashmap?

+15
json powershell
source share
6 answers
 $json = @{Path="C:\temp"; Filter="*.js"} | ConvertTo-Json $hashtable = @{} (ConvertFrom-Json $json).psobject.properties | Foreach { $hashtable[$_.Name] = $_.Value } 

Adapted from PSCustomObject for Hashtable

+26
source share

JavaScriptSerializer is available starting from .NET3.5 (it can be installed in XP, included in Win7 and newer), it is several times faster than Convert-FromJSON, and correctly analyzes 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) } 
+8
source share

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

The code below will analyze 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 } 
+3
source share

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

I tried several JSON sources and I always had the correct hash table.

 $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 
+2
source share

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

0
source share

You can write a function that converts psobject to hashtable.

I wrote an answer here: enter a description of the link here

-one
source share

All Articles