Add new key value pair to JSON file in powershell.

一笑奈何 提交于 2020-07-20 08:35:33

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/45724114/add-new-key-value-pair-to-json-file-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!