-2

In powershell, the following produces correct results.

$foo = @{}
$foo.bar = @{}
$foo.bar.buzz = @("herp","derp")
ConvertTo-Json $foo

{                                     
  "bar":  {                         
    "buzz":  [            
      "herp",  
      "derp"   
    ]            
  }                         
}

However if I add one more level, then the array "buzz" is flattened into a string

$foo = @{}
$foo.bar = @{}
$foo.bar.buzz = @{}
$foo.bar.buzz.bazz = @("herp","derp")
ConvertTo-Json $foo

{
  "bar":  {
    "buzz":  {
      "bazz": "herp derp"
    }
  }
}

Why does powershell flatten Arrays into strings? This issue feels similar to the following SO questions, but none of the purposed solutions solves it.

why-does-powershell-silently-convert-a-string-array-with-one-item-to-a-string

what-determines-whether-the-powershell-pipeline-will-unroll-a-collection

Community
  • 1
  • 1
spuder
  • 17,437
  • 19
  • 87
  • 153
  • 1
    This question was nice to have as the duplicates title didn't describe it well enough. This one has a much better title. – Chris ten Den Jan 11 '19 at 18:36

1 Answers1

3

From ConvertTo-Json documentation

-Depth

Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.

Adding -Depth 9 option to ConvertTo-Json fixes the issue

ConvertTo-Json -Depth 9 $foo

Also, there is a difference between ConvertTo-Json $foo and $foo | ConvertTo-Json. Use ConvertTo-Json $foo whenever possible.

convertto-json-an-array-with-a-single-item

Community
  • 1
  • 1
spuder
  • 17,437
  • 19
  • 87
  • 153