Powershell ConvertTo-JSON missing nested level
It looks like Powershell cuts off data when exporting to JSON if it nests too deep. My object hierchy looks like this:
Main Object
Metadata
More Metadata
Collection of Other object Sources
Collection of data used by these sources
For some reason, when I convert to JSON, powershell exports the Third level (Collection of data used by these sources) as an empty string, even though it is an array of objects with various NoteProperties added to them. For example:
$test = New-Object -TypeName PSObject
$obj = New-Object -TypeName PSObject
$obj | Add-Member -MemberType NoteProperty -Name "Name" -Value "adsf"
$test2 = New-Object -TypeName PSObject
$test2 | Add-Member -MemberType NoteProperty -Name "ArrayTest" -Value @($obj, $obj)
$test3 = New-Object -TypeName PSObject
$test3 | Add-Member -MemberType NoteProperty -Name "ArrayTest" -Value @($obj, $obj, $obj)
$test | Add-Member -MemberType NoteProperty -Name "CollectionTest" -Value @($test2, $test3)
This results in the following JSON String:
PS C:\Users\user\projects\Powershell> $test | ConvertTo-Json
{
"CollectionTest": [
{
"ArrayTest": " "
},
{
"ArrayTest": " "
}
]
}
Converting to XML results in a similar situation:
<?xml version="1.0"?>
<Objects>
<Object Type="System.Management.Automation.PSCustomObject">
<Property Name="CollectionTest" Type="System.Object[]">
<Property Type="System.Management.Automation.PSCustomObject">
<Property Type="System.String">@{ArrayTest=System.Object[]}</Property>
<Property Name="ArrayTest" Type="System.Management.Automation.PSNoteProperty">System.Object[]</Property>
</Property>
<Property Type="System.Management.Automation.PSCustomObject">
<Property Type="System.String">@{ArrayTest=System.Object[]}</Property>
<Property Name="ArrayTest" Type="System.Management.Automation.PSNoteProperty">System.Object[]</Property>
</Property>
</Property>
</Object>
</Objects>
Is there some sort of object nesting limitation in powershell?
Solution 1:
From Get-Help ConvertTo-JSON:
-Depth <Int32>
Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.
Set your -Depth parameter whatever depth you need to preserve your data.