ConvertTo-JSON an array with a single item

前端 未结 4 1007
失恋的感觉
失恋的感觉 2020-12-03 16:58

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 exp

相关标签:
4条回答
  • 2020-12-03 17:11

    Try without the pipeline:

    PS C:\> ConvertTo-Json @('one', 'two')
    [
        "one",
        "two"
    ]
    PS C:\> ConvertTo-Json @('one')
    [
        "one"
    ]
    0 讨论(0)
  • 2020-12-03 17:12

    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.

    0 讨论(0)
  • 2020-12-03 17:17

    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 = "" })
    
    0 讨论(0)
  • 2020-12-03 17:22

    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"
                                  ]
                        }
              }
    }
    
    0 讨论(0)
提交回复
热议问题