Reputation: 8042
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?
Upvotes: 1
Views: 176
Reputation: 1782
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
Upvotes: 3