1

I'm developing for powershell version 2 for backward compatibility. So I've started my shell as powershell -version 2. My goal is to convert JSON in string format to some object I can work with. Here I've found implementation of ConvertTo-Json and ConvertFrom-Json cmdlets.

I have this simple code:

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
    return ,$ps_js.DeserializeObject($item)
}

$jsonString = '{"key1":true, "key2": ["val21", "val22"]}'
$jsonObj = ConvertFrom-Json20 $jsonString
Write-Host $jsonObj.key1
Write-Host $jsonObj.key2

But when I run script containing this code then I get exception for first time for second time it is working:

PS C:\Users\wakatana\Desktop> .\script.ps1
DeserializeObject : Exception calling "DeserializeObject" with "1" argument(s): "Configuration system failed to initialize"
At C:\Users\wakatana\Desktop\script.ps1:10 char:37
+     return ,$ps_js.DeserializeObject <<<< ($item)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException



PS C:\Users\wakatana\Desktop> .\script.ps1
True
val21 val22

Also I've no found this exception under official documentation. What I'm doing wrong?

Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122

1 Answers1

3

This is working: Take add-type on top of the script.

add-type -assembly system.web.extensions

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

function ConvertFrom-Json20([object] $item){ 
    $ps_js=new-object system.web.script.serialization.javascriptSerializer
    return ,$ps_js.DeserializeObject($item)
}

$jsonString = '{"key1":true, "key2": ["val21", "val22"]}'
$jsonObj = ConvertFrom-Json20 $jsonString
Write-Host $jsonObj.key1
Write-Host $jsonObj.key2
f6a4
  • 1,684
  • 1
  • 10
  • 13
  • Thanks. It would certainly be good to know under what circumstances repeated `Add-Type` calls that load the same assembly are _not_ quick, benign no-ops, but it does indeed appear to be the case here, so your fix is effective (+1); note that running the OP's code in PSv5.1 works just fine. – mklement0 Jan 24 '20 at 14:07
  • @f6a4 thank you for reply. Unfortunately I get same error after your suggestions. I've also tried to put `add-type -assembly system.web.extensions` inside `profile.ps1` maybe something is wrong with my shell here is question I had previously https://stackoverflow.com/questions/59258282/powershell-ignores-add-type-unless-it-is-copied-and-pasted-directly-to-console – Wakan Tanka Jan 27 '20 at 06:52