I came across an issue the other day that took me way too long to figure out. I tried 100 different ways of building nested json but all of them failed to expand the object correctly. I posted to Reddit and a kind user pointed me to a simple fix. The cmdlet ConvertTo-Json has a -Depth parameter. This tells the cmdlet how many levels to go in, I had no idea it defaults to only 2 hence my issues. To replicate this you can run the test code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
$L1 = @() $L2 = @() $L3 = @() $L3 += [pscustomobject]@{ 'Level3'="Level3" 'Obj3'="L3" } $L2 += [pscustomobject]@{ 'Level2'="Level2" 'Obj2'=$L3 } $L1 = [pscustomobject]@{ 'Level1'="Level1" 'Obj1'=$L2 } $L1 | ConvertTo-Json { "Level1": "Level1", "Obj1": [ { "Level2": "Level2", "Obj2": "" } ] } $L1 | ConvertTo-Json -Depth 3 { "Level1": "Level1", "Obj1": [ { "Level2": "Level2", "Obj2": [ "@{Level3=Level3; Obj3=L3}" ] } ] } $L1 | ConvertTo-Json -Depth 4 { "Level1": "Level1", "Obj1": [ { "Level2": "Level2", "Obj2": [ { "Level3": "Level3", "Obj3": "L3" } ] } ] } |
For me this was extremely confusing and stumped me for a good amount of time, hopefully this helps someone out!