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
- The most popular use case is to save the data into NoSQL database.
- Convert the runtime value and sending it to a web or API server for further processing.
- Convert the runtime value and save it into database or file to be picked up by another system.
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