3

Code

I have the following script, largely based off information on this site:

cls
if ($PSVersionTable.PSVersion.Major -lt 3) {
    function ConvertTo-Json([psobject] $item){
        [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | out-null
        $ser =  New-Object System.Web.Script.Serialization.JavaScriptSerializer 
        $hashed = @{}
        $item.psobject.properties | %{ $hashed.($_.Name) = $_.Value }
        write-output $ser.Serialize($hashed) 
    }
    function ConvertFrom-Json([string] $json){
        [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | out-null
        $ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
        write-output (new-object -type PSObject -property $ser.DeserializeObject($json))
    }
}

$jsonObj = (new-object -type psobject -property @{
    MyDummyData = @{
        Version = '1.0.4' 
        CreationDate = ("{0:yyyy-MM-ddTHH:mm:ss.fffZ}" -f ((Get-Date).ToUniversalTime())) 
        Demo = 'hello'
        Recurse = @{
            Hello = "hi"
            Greetings = @{
                what = "now"
            }
        }
    }
})

"`n`nobj"
$jsonObj 

"`n`nobj to json"
$jsonx = ConvertTo-Json($jsonObj)
$jsonx 

"`n`njson to obj"
$x = ConvertFrom-Json($jsonx)
$x 

"Compare"
$x -eq $jsonObj

Output

obj

MyDummyData
-----------
{Version, Demo, CreationDate, Recurse}


obj to json
{"MyDummyData":{"Version":"1.0.4","Demo":"hello","CreationDate":"2015-07-23T18:
59:04.265Z","Recurse":{"Greetings":{"what":"now"},"Hello":"hi"}}}


json to obj
{[Version, 1.0.4], [Demo, hello], [CreationDate, 2015-07-23T18:59:04.265Z], ...
Compare
False

Problem

When I test it ConvertTo-Json works perfectly. However ConvertFrom-Json doesn't resolve to the object I started with, but rather gives me an object containing a number of name-value pairs.

Question

Can anyone spot what I've missed; or are the methods proposed on here only suitable in certain scenarios?

Related

Example of existing answer: PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation

Community
  • 1
  • 1
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178

0 Answers0