Zac Zac - 1 month ago 15
JSON Question

JSON Array in PowerShell

Am trying to generate the below JSON string in PowerShell:


[
{
"FirstName": "Test",
"LastName": "Account2"
}
]


The code I have at the moment in PowerShell is:

$Body = @{
@{
FirstName='Test'
LastName='Account2'
}
}


The error I get with this is: Missing '=' operator after key in hash literal.

Answer

The outer [] is a list in JSON and you're trying to use @{}, which is a hashtable in PowerShell. Use @() which is an array (list) in PowerShell:

$Body = @(
    @{
        FirstName='Test'
        LastName='Account2'
    }
)
ConvertTo-Json -InputObject $Body

(and I use -InputObject instead of piping, because PowerShell is obsessed with flattering lists, and drops the list otherwise).