Category Archives: JSON

ConvertTo-Json – Working with the Depth Parameter

A couple of times I have got tripped up by the fact that the Depth parameter for ConvertTo-Json has a default value of 2. So for an object something like this with multiple sub-objects, you will have problems if you don’t specify a higher value for that parameter.

If we send the original object through to ConvertTo-Json with the default value for Depth, then we’ll get the following and you’ll observe that only the first two levels have been dealt with properly:

Using a Depth parameter set to level 10 we get a better result:

So mostly it is just a case of remembering that it may be required to use the Depth parameter. A default value of 2 seems a little low, but I guess there must be a reason for it. In practical terms, I got a bit lazy with this and rather than check what the exact value should be each time, I set a high value which I knew would never be reached, let’s say 200. However, some changes in PowerShell seem to have been introduced since the WMF 5.1 preview / 6.0 alpha which results in the following error:

The maximum depth allowed for serialization is 100.

So it appears that there is now a maximum value of 100 for the Depth parameter. Re-working all mentions from 200 to 100 resolved the problem.