PowerShell: Use ConvertTo-Json on Array with Single Item


You can use the ConvertTo-Json cmdlet in PowerShell to convert an object to a JSON-formatted string.

When using the ConvertTo-Json cmdlet on an array with a single item, using a pipeline will produce a single string:

$my_array | ConvertTo-Json

In order to produce a JSON-formatted string, you must use the following syntax instead:

ConvertTo-Json @my_array

This particular example will format the single item in the array named @my_array into a JSON-formatted string.

The following example shows how to use this syntax in practice.

Example: How to Use ConvertTo-Json on Array with Single Item

Suppose that we create an array named $my_array that contains the name of one basketball team.

Suppose that we attempt to pass this array in a pipeline to the ConvertTo-Json cmdlet to convert the item in this array to a JSON-formatted string:

$my_array = @('Mavs')
$my_array | ConvertTo-Json

The following screenshot shows how to use this syntax in practice:

Notice that this returns a single string.

In order to return a JSON-formatted string, we must use the following syntax instead:

$my_array = @('Mavs')
ConvertTo-Json $my_array

The following screenshot shows how to use this syntax in practice:

PowerShell convertTo-Json single item array

Notice that this returns a JSON-formatted string, just as we intended.

Note #1: If your array has more than one item then you can actually use the pipeline format with the ConvertTo-Json cmdlet without any issues.

Note #2: You can find the complete documentation for the ConvertTo-Json cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Sort by Specific Column
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply