7

How do you add to a JSON array in PowerShell? I'm trying with the following code, but it's complaining with a "Collection was of a fixed size" exception:

$json = @"
[
  {
    "name": "First"
  },
  {
    "name": "Second"
  }
]
"@

$toAdd =@"
{
  "name": "Third"
}
"@

$jobj = ConvertFrom-Json -InputObject $json    
$jobj.Add((ConvertFrom-Json -InputObject $toAdd))

2 Answers 2

19

Just use += instead of Add():

$jobj += (ConvertFrom-Json -InputObject $toAdd)
Sign up to request clarification or add additional context in comments.

1 Comment

This does not work for empty arrays: $json = '[]'. $jobj will be a single object and not an array containing the object.
0

This works.

$js = @"
[
  {
    "name":"First"
  },
  {
    "name":"Second"
  }
]
"@

$toAdd = @"
[
  {
    "name":"Third"
  }
]
"@

$jobj = ConvertFrom-Json -InputObject $js
$jsrc = ConvertFrom-Json -InputObject $toAdd

$jobj = $jobj + $jsrc

Comments

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.