Question:
I have
1 2 3 4 5 6 7 8 9 10 11 |
function Foo($a, $b) { $o = @{} $o.A = $a $o.B = $b $post = @{} $post.X="x" $post.entity =$o $newton::SerializeObject($post) } |
then do
1 2 |
foo "a" "b" |
I get
1 2 |
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
1 2 3 4 5 6 7 8 9 10 |
function Foo2($o) { $post = @{} $post.X="x" $post.entity =$o $newton::SerializeObject($post) } foo2 @{a="a"; b="b"} |
works fine. Also
1 2 3 4 5 6 7 8 9 10 |
function foo3($a, $b) { $o = @{} $o.A = $a $o.B = $b $newton::SerializeObject($o) } foo3 "a" "b" |
works but
1 2 |
foo3 "a" 1 |
fails
The latter can be made to work by doing
1 2 |
$o.B= [Int32]::Parse($b.Tostring()) |
Which all seems very odd
powershell v2 on windows 7, json.net 4.4.5
Answer:
The self referencing loop issue sems to be all about…. the order in which you assign things. The below example works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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} |