Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
Josh Petitt Avatar asked Jan 21 '15 22:01

Josh Petitt


People also ask

What is ConvertFrom-JSON?

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object that has a property for each field in the JSON string. JSON is commonly used by web sites to provide a textual representation of objects.

How do I convert a PowerShell script to JSON?

-InputObjectSpecifies the objects to convert to JSON format. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe an object to ConvertTo-Json . The InputObject parameter is required, but its value can be null ( $null ) or an empty string.

How do I parse JSON data in PowerShell?

PowerShell makes it easy to modify JSON by converting JSON to a PSCustomObject. The object can then be modified easily like any other object. The object can then be exported back out using ConvertTo-Json. Now if we're on a computer without PowerShell 7.1 we try to run the same command in PowerShell 5.1 but it fails!

How do I export PowerShell output to JSON?

PowerShell uses the two cmdlets ConvertTo-JSON and ConvertFrom-JSON to work with JSON files. The ConvertTo-JSON cmdlet converts any possible output to the JSON format and the ConvertFrom-JSON cmdlet converts the JSON input to the custom Object or the hashtable format.


2 Answers

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)
}

If you're getting the error:

Add-Type : Could not load file or assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 or one of its dependencies. The system cannot find the file specified. "

... these registry commands can be run (more details):

   reg add hklm\software\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 /f
   reg add hklm\software\wow6432node\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 /f
like image 68
Edward Avatar answered Oct 28 '22 14:10

Edward


Code with javascriptSerializer return objects with Dictionary inside. Modern convertfrom-JSON (4.0+) return objects only. This code transform deserialize object to modern output :)

function Iterate-Tree($jsonTree) {
    $result = @()
    foreach ($node in $jsonTree) {
        $nodeObj = New-Object psobject
        foreach ($property in $node.Keys) {
            if ($node[$property] -is [System.Collections.Generic.Dictionary[String, Object]] -or $node[$property] -is [Object[]]) {
                $inner = @()
                $inner += Iterate-Tree $node[$property]
                $nodeObj  | Add-Member -MemberType NoteProperty -Name $property -Value $inner
            } else {
                $nodeObj  | Add-Member -MemberType NoteProperty -Name $property -Value $node[$property]
                #$nodeHash.Add($property, $node[$property])
            }
        }
        $result += $nodeObj
    }
    return $result
}

function ConvertFrom-Json20{ 
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$true)][object] $PS_Object
    )

    add-type -assembly system.web.extensions
    $PS_JavascriptSerializer=new-object system.web.script.serialization.javascriptSerializer
    $PS_DeserializeObject = ,$PS_JavascriptSerializer.DeserializeObject($PS_Object) 

    #Convert Dictionary to Objects
    $PS_DeserializeObject = Iterate-Tree $PS_DeserializeObject

    return $PS_DeserializeObject
}
like image 1
Artem Mikryukov Avatar answered Oct 28 '22 13:10

Artem Mikryukov