1

File "array.json": ["bogus"]

PS C:\Users\Me> (Get-Content "array.json" | ConvertFrom-Json -NoEnumerate).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS C:\Users\Me> (Get-Content "array.json" | ConvertFrom-Json).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

While probably useful sometimes, definitely not what I was unexpecting. Answer posted below to help others and avoid confusion.

Robin Johnson
  • 357
  • 2
  • 11

2 Answers2

2

In PowerShell, single item arrays unroll when returned, see: Everything you wanted to know about arrays.

Write-Output -NoEnumerate

PowerShell likes to unwrap or enumerate arrays. This is a core aspect of the way PowerShell uses the pipeline but there are times that you don't want that to happen.

This is probably the biggest pitfall/gotcha in PowerShell and not specific to the ConvertFrom-Json cmdlet, see e.g.: How can I force Powershell to return an array when a call only returns one object?.

The easiest (and most common) way to enforce an array is to use the Array subexpression operator @( ) (rather than the Grouping operator ( )):

@('["bogus"]' | ConvertFrom-Json).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

e.g.:

@('["bogus"]' | ConvertFrom-Json)[0]
bogus

See also questions along with: unroll array single "Array subexpression operator"

As mklement0 points out in this helpful ConvertFrom-Json unpacks arrays with 1 item and behaves oddly with empty object answer, you might also notice the difference in this behaviour with respect to versions prior to PowerShell 7+.

mklement0
  • 382,024
  • 64
  • 607
  • 775
iRon
  • 20,463
  • 10
  • 53
  • 79
0

As you can see in the question, the -NoEnumerate flag (strange name) is required to prevent a code disaster when you attempt to traverse the array...

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.3

Robin Johnson
  • 357
  • 2
  • 11