I'm trying to build JSON output from PowerShell. I use PSCustomObject that contains an array of object. Each of those objects also contains an array of objects.
When I convert this into JSON, the inner array is an empty string.
Here's my code:
$(
$item1 = [PSCustomObject]@{
Name = "name1"
Value = "value1"
}
$item2 = [PSCustomObject]@{
Name = "name2"
Value = "value2"
}
$item3 = [PSCustomObject]@{
Name = "name3"
Value = "value3"
}
$item2 | Add-Member -MemberType NoteProperty -Name ArrayOfObjects -value (New-object System.Collections.Arraylist)
$item2.ArrayOfObjects += $item3
$obj = [PSCustomObject]@{}
$obj | Add-Member -MemberType NoteProperty -Name ArrayOfObjects -value (New-object System.Collections.Arraylist)
$obj.ArrayOfObjects += $item1
$obj.ArrayOfObjects += $item2
$item2 | ConvertTo-Json
$obj | ConvertTo-Json
)
The output is the following:
{
"Name": "name2",
"Value": "value2",
"ArrayOfObjects": [
{
"Name": "name3",
"Value": "value3"
}
]
}
{
"ArrayOfObjects": [
{
"Name": "name1",
"Value": "value1"
},
{
"Name": "name2",
"Value": "value2",
"ArrayOfObjects": ""
}
]
}
While I would expect $obj | ConvertTo-Json to output this:
{
"ArrayOfObjects": [
{
"Name": "name1",
"Value": "value1"
},
{
"Name": "name2",
"Value": "value2",
"ArrayOfObjects": [
{
"Name": "name3",
"Value": "value3"
}
]
}
]
}
Is this a PowerShell limitation on embedded arrays? Is it possible to construct such an object?
PSVersion: 5.1.17763.2183
PSEdition: Desktop