Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell ConvertFrom-Json unexpectedly produces a string instead of object array from single item array containing a string

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.

like image 642
Robin Johnson Avatar asked Dec 06 '25 07:12

Robin Johnson


1 Answers

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+.

like image 52
iRon Avatar answered Dec 08 '25 21:12

iRon