Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
nlowe Avatar asked Mar 07 '14 20:03

nlowe


1 Answers

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.

like image 122
mjolinor Avatar answered Oct 23 '22 00:10

mjolinor