I am struggling to add new element to an existing JSON array using PowerShell scripting. Here is the JSON file structure that I have.
[
{
"Company": [
{
"Finance": [
{
"StaffName": "Name1",
"StaffRating": "Rating1"
}
],
"HR": [
{
"StaffName": "Name1",
"StaffRating": "Rating1"
},
{
"StaffName": "Name2",
"StaffRating": "Rating2"
}
]
}
]
}
]
I am trying to append the following object to the "Company"->"HR" section:
{
"StaffName": "Name3",
"StaffRating": "Rating3"
}
I tried using '+=' with no luck. This code doesn't work, as it removes the contents from the file without throwing any errors:
$FromJSON = Get-Content $JsonfilePath -raw | ConvertFrom-Json
$versionDataFromJSON.Company.HR += [pscustomobject] @{ StaffName= 'Name3'},[pscustomobject] @{ StaffRating= 'Rating3' }
$FromJSON | ConvertTo-Json | Set-Content $JsonfilePath
Here's the JSON that I want to get:
[
{
"Company": [
{
"Finance": [
{
"StaffName": "Name1",
"StaffRating": "Rating1"
}
],
"HR": [
{
"StaffName": "Name1",
"StaffRating": "Rating1"
},
{
"StaffName": "Name2",
"StaffRating": "Rating2"
},
{ "StaffName": "Name3",
"StaffRating": "Rating3"
}
]
}
]
}
]
$FromJSON.Company.HR += [pscustomobject] @{ StaffName= 'Name3'; StaffRating= 'Rating3' }and take note of the-Depthparameter ofConvertTo-Jsoncmdlet.