Home > Enterprise >  "Cannot convert the "System.Object[]" value" when reading and parsing JSON file
"Cannot convert the "System.Object[]" value" when reading and parsing JSON file

Time:09-09

I am trying to read and parse a JSON file in PowerShell and I cannot seem convert a specific array. It works fine with other arrays and I am close to banging my head on the desk.

Here is a very simplified version of what I have. Note that I use exactly the same logic in other places and it works just fine:

Powershell script:

using namespace System.Collections.Generic

class Group{
    [string]$name
}

$json = Get-Content -Raw -Path .\config.json | ConvertFrom-Json
$groups = [List[Group]]$json.groups
Write-Output $json

JSON file:

{
    "groups":[
        {
            "name": "test"
        }
    ]
}

Can anybody please tell me what is going on here?

CodePudding user response:

It's the direct conversion from [object[]] to [List[Group]] that fails in this statement:

[List[Group]]$json.groups

You can solve this with an intermediate conversion from [object[]] to [Group[]] - PowerShell will gladly handle this conversion natively - after which the array satisfies the parameter constraints of one of the List constructors, since [Group[]] implements [IEnumerable[Group]]:

[List[Group]]::new([Group[]]$json.groups)
  • Related