oddity using newtonsoft json.net with powershell

json.net, powershell

Solution

The self referencing loop issue sems to be all about.... the order in which you assign things. The below example works:

function Foo($a, $b)
{
    $o = @{}
    $post = @{}

    $post.entity =$o

    $o.A = $a
    $o.B = $b   

    $post.X="x"

    [Newtonsoft.Json.JsonConvert]::SerializeObject($post)
}

Foo "a" "b"

{"entity":{"A":"a","B":"b"},"X":"x"}

If you convert the type before you pass it in then it will keep your foo3 function generic:

function foo3($a, $b)
{
   $o = @{}
   $o.A = $a
   $o.B = $b
   [Newtonsoft.Json.JsonConvert]::SerializeObject($o)
}


$var2 = [Int32]::Parse((1).Tostring())

Foo3 "a" $var2

{"A":"a","B":1}

Problem

I have ``` function Foo($a, $b) { $o = @{} $o.A = $a $o.B = $b $post = @{} $post.X="x" $post.entity =$o $newton::SerializeObject($post) } ``` then do ``` foo "a" "b" ``` I get ``` Exception calling "SerializeObject" with "1" argument(s): "Self referencing loop detected for property 'Value' with type 'System.Management.Automation.PSParameterizedProperty'. Path 'entity.Members[0]'." ``` however ``` function Foo2($o) { $post = @{} $post.X="x" $post.entity =$o $newton::SerializeObject($post) } foo2 @{a="a"; b="b"} ``` works fine. Also ``` function foo3($a, $b) { $o = @{} $o.A = $a $o.B = $b $newton::SerializeObject($o) } foo3 "a" "b" ``` works but ``` foo3 "a" 1 ``` fails The latter can be made to work by doing ``` $o.B= [Int32]::Parse($b.Tostring()) ``` Which all seems very odd powershell v2 on windows 7, json.net 4.4.5

Original source