2017-08-16 95 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 
相關問題