如何在powershell中替换json文件中的属性

如何在powershell中替换json文件中的属性,json,powershell,Json,Powershell,我在powershell中读取JSON文件、替换值并写回文件或文件时遇到困难 鉴于以下情况: [Object]$QuickJson = @' { "swagger": "1.0", "info": { "version": "0.0.1", "title": "this is a title", "description": "this is a description" }, "basePath": "/test"

我在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"
            }
        }
    }
}
'@
我感兴趣的是用其他东西替换“path”对象中的值。我读取了文件并可以访问对象,但我正在尝试:

[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 --“Name”是只读属性。在C:\scripts\test.ps1:44 char:5 +$info.Name=“$path?code=fsfds” + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +CategoryInfo:InvalidOperation:(:)[],运行时异常 +FullyQualifiedErrorId:PropertyAsignmentException


我已经尝试了几种不同的方法,但仍然没有找到一个好的,或者是可行的解决方案。非常感谢您的任何帮助或指向正确的方向

您可以执行与现在非常类似的操作,只需不更改现有属性而记录初始属性,添加新属性并进行所需的修改,然后将
$MyPSJson.path
设置为自身,排除旧属性,因此它所拥有的只是新属性

#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
请尝试以下操作(PSv3+):

从技术上讲,这需要使用修改的属性名重新创建
.path
对象

它通过枚举原始属性,将它们在修改名称下的值添加到有序哈希表中,在管道完成时,该哈希表将转换为自定义对象(
[pscustomobject]


至于你所尝试的:

无法重命名给定对象的属性-只能更改其属性值

因此,必须使用所需的新特性名称和与原始特性相同的值创建新对象

顺便说一句:
[object]
强制转换在PowerShell中是毫无意义的-它是一个有效的禁止操作。

相比之下,可以使用
[pscustomobject]
强制转换从[ordered]哈希表创建
[pscustomobject]
实例,这是上面使用的技术;从其他类型中选择演员也是一个虚拟的禁忌。

除了对我有效的公认答案之外,我还找到了另一种最初建议的方法,即使用哈希表:

function Convert-JsonFileToHashTable([string]$file) {
    $text = [IO.File]::ReadAllText($file)
    $parser = New-Object Web.Script.Serialization.JavaScriptSerializer
    $parser.MaxJsonLength = $text.length
    $hashtable = $parser.Deserialize($text, @{}.GetType())

    return $hashtable
}

$hashtable = Convert-JsonFileToHashTable (Resolve-Path -Path $DefinitionFile)

$keys = New-Object System.Collections.ArrayList($null)
$keys.AddRange($hashtable["paths"].Keys)
foreach ($key in $keys) 
{
    $newPath = $key + "?code=$Code"
    $hashtable["paths"].$newPath = $hashtable["paths"].$key
    $hashtable["paths"].Remove($key) | Out-Null
}

$json = $hashtable | ConvertTo-Json -Depth 20
Write-Output $json | Out-File $newFile -Encoding utf8

您正在更改路径名吗?
name
字段的类型为
System.Management.Automation.PSNoteProperty
,它是只读的。您需要将额外成员添加到
路径
子项。@ArcSet是,我只需要更改路径name@TheIncorrigible1是的,这就是我遇到的问题,这就是为什么我相信/知道这不是一个正确的方法,可能应该以其他方式来做,只是不知道如何去做你想做的事情,我怀疑您需要将对象转换为哈希表,然后将其替换/转换回json。
function Convert-JsonFileToHashTable([string]$file) {
    $text = [IO.File]::ReadAllText($file)
    $parser = New-Object Web.Script.Serialization.JavaScriptSerializer
    $parser.MaxJsonLength = $text.length
    $hashtable = $parser.Deserialize($text, @{}.GetType())

    return $hashtable
}

$hashtable = Convert-JsonFileToHashTable (Resolve-Path -Path $DefinitionFile)

$keys = New-Object System.Collections.ArrayList($null)
$keys.AddRange($hashtable["paths"].Keys)
foreach ($key in $keys) 
{
    $newPath = $key + "?code=$Code"
    $hashtable["paths"].$newPath = $hashtable["paths"].$key
    $hashtable["paths"].Remove($key) | Out-Null
}

$json = $hashtable | ConvertTo-Json -Depth 20
Write-Output $json | Out-File $newFile -Encoding utf8