如何使用Powershell修改Json
我将以下JSON保存在文件“test.JSON”中: 我想修改“src”元素。而不是:如何使用Powershell修改Json,json,powershell,file-get-contents,Json,Powershell,File Get Contents,我将以下JSON保存在文件“test.JSON”中: 我想修改“src”元素。而不是: "src": [ { "files": [ "src/**.csproj" ] } ], 它需要: "src": [ { "files": [ "*.csproj" ], "cwd":".." } ], 其中
"src": [
{
"files": [
"src/**.csproj"
]
}
],
它需要:
"src": [
{
"files": [
"*.csproj"
],
"cwd":".."
}
],
其中我修改了“files”的第一个元素并添加了“cwd”。这应该是直截了当的,但我正努力在powershell中实现这一点。有人能给我指出这方面的正确方向吗
感谢您提前提供任何提示。您可以执行以下操作:
$JSONObject = Get-Content test.json -Raw | ConvertFrom-Json
$JSONObject.metadata.src.files = ,'*.csproj'
$JSONObject.metadata.src | Add-Member -Name 'cwd' -Value '..' -MemberType NoteProperty
$JSONObject | ConvertTo-Json -Depth 5 | Set-Content test.json
棘手的部分是确保
.files
值是单个元素的数组。可以使用数组子表达式运算符@()
或一元运算符,
,执行以下操作:
$JSONObject = Get-Content test.json -Raw | ConvertFrom-Json
$JSONObject.metadata.src.files = ,'*.csproj'
$JSONObject.metadata.src | Add-Member -Name 'cwd' -Value '..' -MemberType NoteProperty
$JSONObject | ConvertTo-Json -Depth 5 | Set-Content test.json
棘手的部分是确保
.files
值是单个元素的数组。您可以使用数组子表达式运算符@()
或一元运算符,
来实现这一点,这非常有效!!我刚刚在Add成员的末尾添加了“-force”,以防它被多次运行,但这对我来说非常有效,谢谢!!:这工作做得很好!!我刚刚在Add成员的末尾添加了“-force”,以防它被多次运行,但这对我来说非常有效,谢谢!!:D