15

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 [].

3 Answers 3

12

It works without pipelining

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

]
Sign up to request clarification or add additional context in comments.

1 Comment

Interestingly (sadly) it doesn't work if a script (e.g. test.ps1) returns @(). So ConvertTo-Json .\test.ps1 produces nothing.
0

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

Comments

0

PS C:\src\OBAR> ConvertTo_Json @()[] At line:1 char:20

  • ConvertTo_Json @()[]
  •                ~
    

Array index expression is missing or not valid. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingArrayIndexExpression

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.