2017-08-16 93 views
0

我有以下的现有JSON文件:在PowerShell中将新的键值对添加到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 

回答

1

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 
相关问题