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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.