ConvertTo-JSON an array with a single item

Multi tool use
Multi tool use


ConvertTo-JSON an array with a single item



I'm trying to create a JSON-serialized array. When that array contains only one item I get a string, not an array of strings (in JSON).



Multiple Items (works as expected):


PS C:> @("one", "two") | ConvertTo-JSON
[
"one",
"two"
]



Single Item Array (not as expected):


PS C:> @("one") | ConvertTo-JSON
"one"



Am I missing something?




3 Answers
3



Try without the pipeline:


PS C:> ConvertTo-Json @('one', 'two')
[
"one",
"two"
]
PS C:> ConvertTo-Json @('one')
[
"one"
]





Ahh yea. I see how using the pipeline would be ambiguous in this case. Thank you. You made me realize that it's not ConvertTo-JSON specific but a general powershell-array-pipline issue which lead me to: superuser.com/questions/414650/…
– Luggage
Sep 6 '13 at 18:03






@Luggage If only there was sanity: @(@(1)) | ConvertTo-Json -- still "NOPE"
– user2864740
Oct 31 '17 at 4:21


@(@(1)) | ConvertTo-Json



I hit this problem as well but it was because my structure was too deep and ConvertTo-Json flattens everything below a certain depth to a string.



For example:


PS C:> $MyObject = @{ "a" = @{ "b" = @{ "c" = @("d") } } }
PS C:> ConvertTo-Json $MyObject
{
"a": {
"b": {
"c": "d"
}
}
}



To fix this, you can pass a larger value to -Depth


PS C:> ConvertTo-Json $MyObject -Depth 100
{
"a": {
"b": {
"c": [
"d"
]
}
}
}



Faced the same issue today. Just to add, if you have an object like this


@{ op="replace"; path="clientName"; value="foo"}



then you have to specify it as


ConvertTo-Json @( @{ op="replace"; path="clientName"; value="foo"} )



The double @s can become confusing sometimes.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

fB2QJp4FE7d3CR0x HyhW uBQFa7wMsiGxAGy H6Me3t6N8KLmJP,bP93BmVdELg wKHGvIa gvelB3wWybe2UEc
17l 0zJIPLL53HKE5940Qa B,DoWVOF,TGKNam6,qzT9NMhs,aX nZJMm49jOpKljd0MydcuC

Popular posts from this blog

Rothschild family

Boo (programming language)