Skip to content

Instantly share code, notes, and snippets.

@mrpullen
Created January 20, 2016 05:13
Show Gist options
  • Save mrpullen/4eab064baf0aa56c5f50 to your computer and use it in GitHub Desktop.
Save mrpullen/4eab064baf0aa56c5f50 to your computer and use it in GitHub Desktop.
Powershell to convert to / from JSON string to ordered hashtable.
function Compare-Hashtables {
param([hashtable]$primary,
[hashtable]$secondary
)
foreach($key in $primary.Keys) {
if($secondary.Contains($key)) {
if($primary[$key].GetType() -eq [System.Collections.Specialized.OrderedDictionary] -and
$secondary[$key].GetType() -eq [System.Collections.Specialized.OrderedDictionary] ) {
$res = Compare-Hashtables -primary $primary[$key] -secondary $secondary[$key]
if($res -eq $false) {
return $res
}
else {
Write-Host "$($key): $($primary[$key]) -eq $($secondary[$key])"
}
}
elseif($primary[$key].GetType().BaseType -eq [System.Array] -and $secondary[$key].GetType().BaseType -eq [System.Array]) {
$primaryArray = $primary[$key]
$secondaryArray = $secondary[$key]
foreach($item in $primaryArray) {
if($secondaryArray.Contains($item)) {
Write-Host "$($item) -eq $($item)"
}
else {
return $false
}
}
}
elseif($primary[$key] -eq $secondary[$key]) {
Write-Host "$($key): $($primary[$key]) -eq $($secondary[$key])"
}
else {
Write-Host "Value not matching $($primary[$key]) -- $($secondary[$key])"
return $false
}
}
else {
Write-Host "Key not found $($key)"
return $false
}
}
return $true
}
function ConvertFrom-JsonToHashtable {
param([string]$Json)
$hash = ConvertFrom-Json -InputObject $Json | ConvertPSObjectToHashtable
return $hash
}
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 = [ordered]@{}
foreach ($property in $InputObject.PSObject.Properties)
{
$hash[$property.Name] = ConvertPSObjectToHashtable $property.Value
}
$hash
}
else
{
$InputObject
}
}
}
$test = [ordered]@{
Name = 'John Doe'
Age = 10
Amount = 10.1
MixedItems = (1,2,3,"a")
NestedHash = [ordered]@{
nestedkey = "nextedvalue"
nextttie = "test"
}
}
$jsonString = ConvertTo-Json -InputObject $test
Write-Host $jsonString
$test2 = ConvertFrom-JsonToHashtable -Json $jsonString
Compare-Hashtables -primary $test -secondary $test2
##Compare-Object -ReferenceObject $test -DifferenceObject $test2 -IncludeEqual
@PSLuv
Copy link

PSLuv commented Sep 10, 2020

Just what I was needing...Great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment