我有一个包含以下内容的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
最佳答案
将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
关于json - 将新的键值对添加到Powershell中的JSON文件中。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724114/