Welcome to ciysys blog

Tricky ConvertTo-Json in Powershell

Published on: 11th May 2020

Updated on: 16th Jan 2022

Explanation

ConvertTo-JSON command is very useful for generating any runtime value into JSON format. Then, sending the JSON data to any web server for further process.

For example, the following code convert an array into JSON format:

# save the to json format
$list = @(
    "Apple",
    "Banana"
)

$list | ConvertTo-Json

And the output will look like this:

[
    "Apple",
    "Banana"
]

But, there is a catch in the following situation where it does not convert an array into JSON format. Instead, it just returns a string.

$trick = @(
    "Coconut"
)

$trick | ConvertTo-Json

And the output will look like this:

"Coconut"

This is not a mistake of the above code. Instead, the correct code should look like the following:

ConvertTo-Json -InputObject $trick

Output:

[
    "Coconut"
]

Use case

Jump to #POWERSHELL blog

Author

Lau Hon Wan, software developer.