Tricks in using Powershell ConvertTo-Json


Explanation

ConvertTo-JSON command is very useful for generating any runtime value into JSON format. Then, sending the JSON data to any web API 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 way to convert the above array should look like the following:

ConvertTo-Json -InputObject $trick

Output:

[
    "Coconut"
]

Use case

Conclusion

We believe using JSON format is better and easier to integrate with any web API system as compared to XML format.

Back to #POWERSHELL blog

Back to #blog listing