skip to Main Content

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

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

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

PS C:UsersMe> (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.

2

Answers


  1. Chosen as BEST ANSWER

    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


  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/gotha 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 then 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"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search