r/PowerShell • • 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 10

to 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 10

Any idea?

EDIT: thank you /u/y_Sensei and /u/ankokudaishogun. Both approaches worked fine.

7 Upvotes

12 comments sorted by

View all comments

Show parent comment

2

u/icepyrox Feb 14 '25

Ah yea. Its still a single item in an array and the pipe passes the one item and says "done" so the conversion doesn't know its an array unless you specify -AsArray (or pass it via -InputObject rather than via pipe).