Question

Converting arrays to JSON string in PowerShell couldn't be more simple:

@(1,2,3) | ConvertTo-Json

Produces:

[
    1,
    2,
    3
]

However if the array is empty the result is an empty string:

@() | ConvertTo-Json

Results an empty string instead of [].

Was it helpful?

Solution

It works without pipelining

PS C:\> ConvertTo-Json @()
[

]

OTHER TIPS

This is a use case for the unary comma operator, https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2

The pipeline is breaking the array apart. In the first example, the array is broken apart into its integer values as it passes through the pipeline (I'm not sure of what the actual mechanics of it being reassembled on the other side are: if it's the pipeline acting logically seeing three integers grouped together or if it's some interpretation being done by the receiving cmdlet itself). Regardless, using the unary operator ',' creates an array of one element. When used as either , @(1, 2, 3) or , @() it creates a container array which is broken apart by the pipeline still, but the sub-arrays are the objects being passed through and preserved as intended to be interpreted by the ConvertTo-Json cmdlet properly. Assuming your array is stored in a variable like $myArray, the following general code will work for all situations:

, $myArray | ConvertTo-Json
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top