使用PowerShell替换JSON文件字符串失败,请求技术协助
问题解决:替换JSON中的
$APIConnectionName字符串 原JSON文件(InitialApiConnectionTemplateFile.json)
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "connections_$APIConnectionName_name": { "defaultValue": "$APIConnectionName", "type": "String" } }, "variables": {}, "resources": [] }
无效的PowerShell脚本
$JsonData = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json | ConvertFrom-Json $JsonData -replace '$APIConnectionName', 'TestValue' $JsonDataNew = $JsonData | ConvertTo-Json -depth 100 Write-Host "$JsonDataNew "
问题原因
ConvertFrom-Json会将JSON转换成PowerShell自定义对象,直接对对象使用-replace只会修改对象的字符串表示,不会改变对象内部的属性值,原对象根本没被修改。- 字符串
$APIConnectionName中的$是正则表达式的特殊字符(表示行尾匹配),直接用-replace无法正确匹配目标内容。
解决方案
方案一:直接操作JSON字符串(全局替换)
不需要解析成对象,直接对文件内容做字符串替换,适合不需要精准控制替换位置的场景:
# 读取文件为单字符串(-Raw参数避免换行拆分) $JsonString = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json -Raw # 使用[regex]::Escape处理特殊字符$,确保准确匹配 $JsonStringReplaced = $JsonString -replace [regex]::Escape('$APIConnectionName'), 'TestValue' # 输出结果 Write-Host $JsonStringReplaced # 若需保存到新文件,执行: # $JsonStringReplaced | Out-File "UpdatedApiConnectionTemplate.json" -Encoding utf8
方案二:操作JSON对象(精准修改)
解析成对象后针对性修改参数键名和默认值,避免误替换其他内容,适合需要精确控制修改位置的场景:
# 读取并解析JSON为对象 $JsonData = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json | ConvertFrom-Json # 定位并修改参数的键名 $oldParamKey = $JsonData.parameters.PSObject.Properties.Name | Where-Object { $_ -contains '$APIConnectionName' } $paramValue = $JsonData.parameters.$oldParamKey $JsonData.parameters.PSObject.Properties.Remove($oldParamKey) $newParamKey = $oldParamKey -replace [regex]::Escape('$APIConnectionName'), 'TestValue' $JsonData.parameters | Add-Member -MemberType NoteProperty -Name $newParamKey -Value $paramValue # 修改参数的defaultValue属性 $JsonData.parameters.$newParamKey.defaultValue = 'TestValue' # 转换回JSON并输出 $JsonDataNew = $JsonData | ConvertTo-Json -Depth 100 Write-Host $JsonDataNew
内容的提问来源于stack exchange,提问作者Joy
相关产品推荐
相关产品推荐

