13

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.

2 Answers 2

30

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That works a treat. I have also updated the script to use the InputObject as you mentioned. Thanks again!
This helped me with a similar issue as well, thanks!
Good point about the -InputObject Vs Piping. Solved my issue.
1

I had some problems adding new items to the Powershell list. I tried to add an item using the .add() function. This returned the error "Collection was of a fixed size."

Adding items to the list is just simple by using the += symbol.

$Body += @{FirstName='Test2'; LastName='Account3'}

That simple.

1 Comment

Careful, += is supposed to be pretty expensive because it creates a new array with the new element appended to the end. Then replaces the old array with the new one. See stackoverflow.com/questions/14620290/array-add-vs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.