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.
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+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With