在 powershell 中向 JSON 文件添加新的键值对. [英] Add new key value pair to JSON file in powershell.

查看:86
本文介绍了在 powershell 中向 JSON 文件添加新的键值对.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的 JSON 文件,内容如下:

I have an existing JSON file with the following:

{
    "buildDate":  "2017-08-16",
    "version":  "v1.2.0"
}

如何将新的键值对添加到现有的 JSON 文件中?比如我想拿上面的JSON,最后得到这个:

How do you add new key-value pairs to an existing JSON file? For example, I would like to take the above JSON, and end up with this:

{
    "buildDate":  "2017-08-16",
    "version":  "v1.2.0",
    "newKey1": "newValue1",
    "newKey2": "newValue2"
}

我目前使用以下代码写入 JSON:

I currently write to JSON with the following code:

@{buildDate="2017-08-16"; version="v1.2.0"} | ConvertTo-Json | Out-File .\data.json

推荐答案

将 JSON 数据转换为 PowerShell 对象,添加新属性,然后将对象转换回 JSON:

Convert the JSON data to a PowerShell object, add the new properties, then convert the object back to 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

这篇关于在 powershell 中向 JSON 文件添加新的键值对.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆