json - 将新的键值对添加到Powershell中的JSON文件中。

标签 json powershell scripting

我有一个包含以下内容的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/

相关文章:

json - 如何在 Mandrill 模板中嵌入 Google 架构脚本

json - dotnet 编译错误; aspnetcore.mvc.razor.viewcompliation.rsp 退出,代码为 1

java - 使用新标准 javax.json 将 Pojos 序列化为 JSON

powershell - 使用 SilentlyContinue 时如何处理写入信息管道输出

c# - 如何为我的应用程序添加可编程性

javascript - 是否可以使用 Lua/Javascript 脚本使用新变量扩展 C# 对象?

jQuery parseJson 对象方向(IE 和 Firefox 与 Opera 和 Chrome)

excel - Powershell脚本将txt转换为xlsx

azure - 您可以在 Azure Devops 的内联 Azure Powershell 脚本中使用 IF 语句吗?

scripting - Powershell循环卡住,在不需要输入时等待输入