我有一个现有的JSON文件,其中包含以下内容:
{
"buildDate": "2017-08-16",
"version": "v1.2.0"
}
如何向现有JSON文件添加新的键值对?例如,我想采用上面的JSON,最后得到这个:
{
"buildDate": "2017-08-16",
"version": "v1.2.0",
"newKey1": "newValue1",
"newKey2": "newValue2"
}
我目前使用以下代码写入JSON:
@{buildDate="2017-08-16"; version="v1.2.0"} | ConvertTo-Json | Out-File .\data.json
答案 0 :(得分:4)
将JSON数据转换为PowerShell对象,添加新属性,然后将对象转换回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