I´m writing a script in powershell 2.0 and an upgrade to 3.0 or higher is not possible right now. In this script I try to serialize some data to JSON with the code from this link (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)
}
My problem is that I somehow get a circular reference and I really don´t know why. I set up a litte piece of test data and the structure looks in powershell like this:
$testRoot = @{
"id" = "1"
"children" = @(
@{
"id" = "2"
"children" = @(
@{
"id" = "2";
};
@{
"id" = "3";
}
);
};
@{
"id" = "4"
"children" = @(
@{
"id" = "5";
}
);
}
)
}
I know it looks junky, but I just need it in this format.
The structures I need to serialize have a few more layers, so even more "children" and there is the point where it gets strange.
When I try this:
ConvertTo-Json20 $testRoot
everything works fine. The structure gets parsed like this:
{
"id":"1",
"children":[
{
"id":"2",
"children":[
{
"id":"2"
},
{
"id":"3"
}
]
},
{
"id":"4",
"children":[
{
"id":"5"
}
]
}
]
}
But now comes the problem. As mentioned the structure has more layers, so I try this which just sets the data in an array.
ConvertTo-Json20 @($testRoot)
But it does not work I just get an error message saying:
Exception in method "Serialize" with 1 argument(s):
"While serializing an object of type "System.Management.Automation.PSParameterizedProperty" a circular reference was discovered."
At C:\Users\a38732\Desktop\Temp.ps1:34 symbol:28
+ return $ps_js.Serialize <<<< ($item)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
(I translated the error message from german, so there might be some words different in the english version...)
[object]
. – Inclinatory@( )
array subexpression operator is special. To quote: "Returns the result of one or more statements as an array." e.g.@(Get-Date; Start-Sleep -s 1; Get-Date)
. And since anarray
is aobject
, the function is perfectly valid. One problem is thatJavaScriptSerializer.Serialize()
is useless for anything but simple JSON. – UsurerConvertTo-Expression
cmdlet from the PowerShell Gallery which is downwards compatible with PSv2.0. The results can easily be invoked (deserialized) withInvoke-Expression
or just an ampersand (&
) or dot sourcing a.ps1
file containing the results. – Mcclelland