如何使用 PowerShell 更新 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35865272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I update JSON file using PowerShell
提问by Neo
I have one json file mytest.jsonlike below I want to update values using PowerShell script
我有一个mytest.json像下面这样的json 文件我想使用更新值PowerShell script
update.json
更新文件
{
"update": [
{
"Name": "test1",
"Version": "2.1"
},
{
"Name": "test2",
"Version": "2.1"
}
]
}
I want to write a PowerShell script where if Name=="test1" I want to update Version= "3"How can i do it using parameters?
我想编写一个 PowerShell 脚本,if Name=="test1" I want to update Version= "3"我如何使用参数来完成它?
回答by JPBlanc
Here is a way :
这是一种方法:
$a = Get-Content 'D:\temp\mytest.json' -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'test1'){$_.version=3.0}}
$a | ConvertTo-Json -depth 32| set-content 'D:\temp\mytestBis.json'
According to @FLGMwt and @mikemaccana I improve the ConvertTo-Jsonwith -depth 32because the default depth value is 2 and for object deeper than 2 you will receive class informations in spite of objects.
根据@FLGMwt 和@mikemaccana,我改进了ConvertTo-Json,-depth 32因为默认深度值为 2,对于深度大于 2 的对象,尽管有对象,您仍会收到类信息。

