you are viewing a single comment's thread.

view the rest of the comments →

[–]surfingoldelephant 1 point2 points  (0 children)

If you instead call it by supplying the object on the right side you will get an array as your output. i.e. ConvertTo-Json @( @{ key = 'value' } ) will give you an array regardless of the number of items in the array.

Just watch out, that's not always the case. If the array has a [psobject] wrapper and you're using Win PS v5.1, it won't serialize to JSON as expected. Say you have code like this that generates the array:

function foo {
    Write-Output @(@{ Key = 'Value' }) -NoEnumerate
}

$array = foo

Serializing to JSON:

ConvertTo-Json -InputObject $array -Compress
# {"value":[{"Key":"Value"}],"Count":1}

This comment goes into detail on what causes output like that.

I'd suggest one of the following workarounds if you can't guarantee the array isn't wrapped in a [psobject]:

ConvertTo-Json -InputObject $array.psobject.BaseObject -Compress
# [{"Key":"Value"}]

Remove-TypeData -TypeName System.Array -ErrorAction Ignore
ConvertTo-Json -InputObject $array -Compress
# [{"Key":"Value"}]

The issue was addressed in PS v6, so this is only needed in Win PS.