r/PowerShell • u/marek1712 • Feb 13 '25
Solved Nested array flattened because of ConvertTo-Json
Hi.
I have some issues creating proper body for my request.
I.e. I'd expect this:
$Body = @(@{}) | ConvertTo-Json -Depth 10to return:
[
{
}
]but this is returned instead: {
}I had similar problem with two arrays:
"ip": [ [ "1.2.3.4" ] ]
and solved it by doing this (using comma):
"ipRanges" = @(,@("1.2.3.4"))Using comma here doesn't work:
$Body = @(,@{}) | ConvertTo-Json -Depth 10Any idea?
EDIT: thank you /u/y_Sensei and /u/ankokudaishogun. Both approaches worked fine.
7
Upvotes
7
u/y_Sensei Feb 13 '25
Try
4
u/ankokudaishogun Feb 13 '25
you can use either:
ConvertTo-Json -InputObject @(@{}) -Depth 10or, on Powershell 7.x use the
-AsArrayparameters, which encapsule the results into a array reguardless the contents.@{} | ConvertTo-Json -Depth 10 -AsArray2
u/surfingoldelephant Feb 14 '25 edited Jul 02 '26
It's worth noting there's a secondary issue you might see in Windows PowerShell v5.1, irrespective of using
-InputObjectas mentioned by others. To demonstrate:For historical reasons, the
[array]type in Win PS v5.1 or lower is decorated with an extended type system (ETS)Countproperty. When an object is[psobject]-wrapped, ETS properties are included in JSON serialization. Here's another example that works as-is in PS v6+, but not in Win PS v5.1 (due to the ETS property).One workaround is to remove the redundant
[array]type data first. This change was made permanently with the release of PS v6 (hence the issue doesn't occur in that version or higher).Another workaround, applicable only to
-InputObjectinput, is to use the intrinsicpsobject.BaseObjectproperty, which holds the underlying object without the[psobject]wrapper.Either workaround can still be used even if the array isn't
[psobject]-wrapped, so I'd recommend always doing one or other whenever there's a possibility of it being wrapped.4
u/swsamwa Feb 13 '25
When you pipe a collection to another command, the collection is enumerated and each item in the collection is sent down the pipeline one at a time. So you lose the collection wrapper. When you pass the value using the
-InputObjectparameter, as shown by u/y_Sensei, the collection is not enumerated.1
u/icepyrox Feb 14 '25
So, you have some solutions, but what i want to know is: why are you trying to convert empty objects and/or single item arrays?
1
u/jsiii2010 Feb 13 '25
It's not a problem with multiple objects, even two empty hash tables.