Json circular reference in powershell 2.0 with javascriptSerializer Json circular reference in powershell 2.0 with javascriptSerializer json json

Json circular reference in powershell 2.0 with javascriptSerializer


One problem is the use of the JavaScriptSerializer class itself. As of this date the documentation itself concedes it should not be used to serialize nor deserialize JSON. To quote:

Json.NET should be used serialization and deserialization.

If you're able to use third-party libraries like Json.NET, here's a simple function that does what you need given the data structure in the OP:

function ConvertTo-JsonNet {   [CmdletBinding()]    param(        [Parameter(Mandatory)] $object,        [Parameter(Mandatory)] [string]$jsonNetPath,        [switch]$indent,        [switch]$preserveReferencesHandling    )    Add-Type -Path $jsonNetPath;    $formatting = if ($indent.IsPresent) { [Newtonsoft.Json.Formatting]::Indented; }    else { [Newtonsoft.Json.Formatting]::None; }    $settings = New-Object Newtonsoft.Json.JsonSerializerSettings;    if ($preserveReferencesHandling.IsPresent) {         $settings.PreserveReferencesHandling = [Newtonsoft.Json.PreserveReferencesHandling]::Objects;    }    [Newtonsoft.Json.JsonConvert]::SerializeObject($object, $formatting, $settings);}

Simple usage, assuming Newtonsoft.Json.dll is in the same directory as your script:

$dllPath = Join-Path $PSScriptRoot 'Newtonsoft.Json.dll';ConvertTo-JsonNet @($testRoot) $dllPath;

Output:

[{"id":"1","children":[{"id":"2","children":[{"id":"2"},{"id":"3"}]},{"id":"4","children":[{"id":"5"}]}]}]

You can manually download the .dll from the nuget package project site. It has a .nupkg file extension, but it's a zipped archive, so rename the extension to .zip and you're set. In the lib sub-directory there are .dll files for .NET versions from 2.0 through 4.5.