json - 如何在powershell中替换json文件中的属性
问题描述
我很难在 powershell 中读取 JSON 文件,替换值并写回文件或文件。
鉴于以下情况:
[Object]$QuickJson = @'
{
"swagger": "1.0",
"info": {
"version": "0.0.1",
"title": "this is a title",
"description": "this is a description"
},
"basePath": "/test",
"paths" : {
"/GetSomething": {
"get": {
"name" : "test01"
}
},
"/GetSomethingElse" : {
"get": {
"name" : "test02"
}
},
"/GetAnotherThing": {
"get": {
"name" : "test03"
}
}
}
}
'@
我在这里感兴趣的是用其他东西替换“路径”对象中的值。我读取了文件并且可以使用我正在尝试的方法访问该对象:
[object]$MyPSJson = ConvertFrom-Json -InputObject $QuickJson
foreach($info in $MyPSJson.paths.PSObject.Properties)
{
$path = $info.Name
Write-Host "path: $path"
$info.Name = "$path?code=fsfsfsfsfsfdfds"
Write-Host $info.Name
}
我不知道那些“路径”将是什么,我需要获取现有值并向其附加一个代码值,因此我需要能够遍历所有路径并进行替换。当我尝试上述方法时,出现错误:
路径:/GetSomething --“名称”是只读属性。在 C:\scripts\test.ps1:44 char:5 + $info.Name = "$path?code=fsfsfsfsfsfdfds" + ~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyAssignmentException
我已经尝试了几种不同的方法,但还没有提出一个好的或可行的解决方案。非常感谢任何帮助或指出正确的方向。
解决方案
您可以做一些与您现在所拥有的非常相似的事情,而不是更改您记录初始属性的现有属性,添加带有您想要的修改的新属性,然后设置$MyPSJson.paths
为自身,不包括旧属性,所以它所拥有的都是新的特性。
#Find initial paths
$Paths=$MyPSJson.paths.psobject.Properties.Name
#Add new paths with the modification to the name, and set the value to the same as the old path
$Paths|%{Add-Member -InputObject $MyPSJson.paths -NotePropertyName "$_`?code=fsfsfsfsfsfdfds" -NotePropertyValue $MyPSJson.paths.$_}
#Set the paths object to itself, excluding the original paths
$MyPSJson.paths = $MyPSJson.paths|Select * -ExcludeProperty $Paths
推荐阅读
- javascript - 迷宫不循环的 BFS 算法 - Javascript
- .htaccess - htaccess 使用 www 和路径重定向
- java - 等到状态出现在 Java for 循环中
- php - 如何在php中将字符串转换为日期
- bash - 将具有相同键的变量添加到数组时枚举?
- python - Python Django:填写表单字段总是在POST上抛出错误“此字段是必需的”
- powershell - 无法将“System.String”类型的“/Action:”值转换为“System.Management.Automation.ScriptBlock”类型
- python - 从python中的路径获取子文件名而不使用split
- r - 如何使用 R 中的 ggplot2 在任何给定时间绘制多个数量的平均值?
- css - 使用 css 网格显示项目并构建第一个固定列