1

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Ok this worked. But why is it that other arrays work just fine using the exact same logic? I have a users array which contains name and password and Powershell manages to parse this just fine. I don't do anything differently, only the class name and the properties are different.
@LeonidasFett Update your question with the example you're describing if you want me to explain why it doesn't fail in the same way :)
That's weird, I swear it used to work before with the users array. Now, when I execute my script with the users array, I get the same error. This is giving me a headache. XD
Even works without new(), using only cast syntax: [List[Group]] [Group[]] $json.groups
It does indeed, although PowerShell ends up doing the exact same thing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.