Working with ConvertTo-Json output issues

As you are aware, we can use ConvertTo-Json cmdlet to convert an object to Json output format using PowerShell. However, there is something you need to be aware of while using conversion. By default, it does not work with very large objects (containing of multiple sub-objects) and converts them properly. This is because of the fact that the Depth parameter for ConvertTo-Json has a default value of 2. Let’s understand what this means.

For our example, we’ll create a JSON file with below details first and save it on to your local machine as new-json.json


This is part of the one of the deployment templates used for Azure. Now, run below command on the PowerShell prompt to import the content into a variable:

$var = (Get-Content .\new-json.json) | ConvertFrom-Json

If we want to see whether its properly imported or not, we can use Get-Member cmdlet:

$var | gm

 TypeName: System.Management.Automation.PSCustomObject

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
$schema NoteProperty string $schema=
contentVersion NoteProperty string contentVersion=
outputs NoteProperty System.Management.Automation.PSCustomObject outputs=@{return=}
parameters NoteProperty System.Management.Automation.PSCustomObject parameters=@{firstArray=; secondArray=}
resources NoteProperty Object[] resources=System.Object[]

This would confirm that object is properly imported. Let’s modify the contentVersion property to some other value by running below command:

$var.contentVersion = ""
$var | ConvertTo-Json | Out-file Json3.json

Let’s view the content of the output file. It should be something like this:

If you look closely, the value of parameters.firstarray.defaultValue and parameters.secondArray.defaultValue is converted to string. Whereas in the original file, it was passed as an array. So this is because by default the depth parameter has a value of 2 and therefore the serialization is limited to only 2 levels.

Now, let’s convert the output using a depth value of 5 (just being lazy, you can count levels if you want to):

$var | ConvertTo-Json -Depth 5 | Out-file Json4.json

Again, let’s observe file output:

This time we can see that it has been properly processed. Do note that maximum value allowed for serialization is 100 as of PowerShell 5.1. So you cannot have depth levels higher than that. Although this should be able to satisfy most of the objects you come across.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s