Tricky ConvertTo-Json in Powershell
ConvertTo-JSON is very useful for generating any runtime value into JSON format.
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 on the following situation where it does not convert the 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"
]
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 on the following situation where it does not convert the 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"
]
Comments
Post a Comment