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?


Solution 1:

Try without the pipeline:

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

Solution 2:

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"
                              ]
                    }
          }
}

Solution 3:

I just had the same issue and found out, that you can just append an -AsArray to the ConvertTo-Json command. Examples:

❯ @("one") | ConvertTo-Json -AsArray       
[
  "one"
]
❯ @("one", "two") | Convert-ToJson -AsArray
[
  "one",
  "two"
]

Solution 4:

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.

Solution 5:

I faced this issue with an array that was a child in an object. The array had one object in it, and ConvertTo-Json was removing the object in the array.

Two things to resolve this:

I had to set the -Depth parameter on ConvertTo-Json

$output = $body | ConvertTo-Json -Depth 10

I had to create the object in the array as a hashtable and then convert that to an object

$myArray.Add([pscustomobject]@{prop1 = ""; prop2 = "" })