Reputation: 3636
I have an existing JSON file with the following:
{
"buildDate": "2017-08-16",
"version": "v1.2.0"
}
How do you add new key-value pairs to an existing JSON file? For example, I would like to take the above JSON, and end up with this:
{
"buildDate": "2017-08-16",
"version": "v1.2.0",
"newKey1": "newValue1",
"newKey2": "newValue2"
}
I currently write to JSON with the following code:
@{buildDate="2017-08-16"; version="v1.2.0"} | ConvertTo-Json | Out-File .\data.json
Upvotes: 7
Views: 23581
Reputation: 200493
Convert the JSON data to a PowerShell object, add the new properties, then convert the object back to JSON:
$jsonfile = 'C:\path\to\your.json'
$json = Get-Content $jsonfile | Out-String | ConvertFrom-Json
$json | Add-Member -Type NoteProperty -Name 'newKey1' -Value 'newValue1'
$json | Add-Member -Type NoteProperty -Name 'newKey2' -Value 'newValue2'
$json | ConvertTo-Json | Set-Content $jsonfile
Upvotes: 21