3

I'm using there functions to serialize and deserialize objects in Powershell 2.0 from question PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation

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

But when i run example:

$json = "[{'a':'b'},{'c':'d'}]"
$o = ConvertFrom-Json20 $json
$newJson = ConvertTo-Json20 $o

I've got error:

Exception calling "Serialize" with "1" argument(s): "A circular reference was detected while serializing an object of t
ype 'System.Management.Automation.PSParameterizedProperty'."
At line:4 char:28
+     return $ps_js.Serialize <<<< ($item)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

How can I resolve this error?

P.S. I apologize in advance. What was not able to add a comment to the original question ...

Community
  • 1
  • 1

1 Answers1

2

There are two problem in code:

  1. PowerShell enumerate collections, so instead of one array ConvertFrom-Json20 return two dictionaries. It is not big deal by itself, but:
  2. return statement in PowerShell v2 wrap returned objects by PSObject. As result $o contain array with two PSObject, and JSON serializer can not work with them properly.

To prevent collection enumeration you can use unary comma operator. This operator create array with single element, and array will be enumerated instead of collection. And since PowerShell return output even without return statement, you can just remove it.

user4003407
  • 21,204
  • 4
  • 50
  • 60
  • Can you explain that part with "use unary comma operator"? I cannot figure out how I can solve the similar problem. – Azimuth May 20 '21 at 13:01