Question:
I have an existing JSON file with the following:
1 2 3 4 5 |
{ "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:
1 2 3 4 5 6 7 |
{ "buildDate": "2017-08-16", "version": "v1.2.0", "newKey1": "newValue1", "newKey2": "newValue2" } |
I currently write to JSON with the following code:
1 2 |
@{buildDate="2017-08-16"; version="v1.2.0"} | ConvertTo-Json | Out-File .\data.json |
Answer:
Convert the JSON data to a PowerShell object, add the new properties, then convert the object back to JSON:
1 2 3 4 5 6 7 8 9 |
$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 |