Josh Petitt Josh Petitt - 5 months ago 342
JSON Question

PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation

I would like to monkeypatch a PowerShell 2.0 environment where the upgrade to 3.0 is not possible at this time.

I am looking for a PowerShell 2.0 script implementation of the

ConvertFrom-Json
cmdlet and
ConvertTo-Json
cmdlet that are in PowerShell 3.0.

I am most interested in the
ConvertFrom-Json
, but
ConvertTo-Json
would also be nice.

Answer
function ConvertTo-Json20([object] $item){
    add-type -assembly system.web.extensions
    $ps_js=new-object system.web.script.serialization.javascriptSerializer
    return $ps_js.Serialize($item)
}

function ConvertFrom-Json20([object] $item){ 
    add-type -assembly system.web.extensions
    $ps_js=new-object system.web.script.serialization.javascriptSerializer

    #The comma operator is the array construction operator in PowerShell
    return ,$ps_js.DeserializeObject($item)
}
Comments