首页 > 解决方案 > 如何在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

我已经尝试了几种不同的方法,但还没有提出一个好的或可行的解决方案。非常感谢任何帮助或指出正确的方向。

标签: jsonpowershell

解决方案


您可以做一些与您现在所拥有的非常相似的事情,而不是更改您记录初始属性的现有属性,添加带有您想要的修改的新属性,然后设置$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

推荐阅读