Add new key value pair to JSON file in powershell.
14,483
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
Author by
Roka545
Updated on June 26, 2022Comments
-
Roka545 almost 2 years
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