【问题标题】:Add new key value pair to JSON file in powershell.将新的键值对添加到 powershell 中的 JSON 文件。
【发布时间】:2018-01-25 05:16:29
【问题描述】:

我有一个现有的 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 scripting


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2013-10-15
      相关资源
      最近更新 更多