Powershell:修改 JSON 文件中的键值对



如何使用Powershell修改JSON文件中的键值对?

我们正在尝试修改数据库连接,有时它可以是两级嵌套深度,有时它可以是三级深度。

试图利用这个答案,

目前,我们正在多个json文件中切换服务器,因此我们可以在不同的服务器环境中进行测试。

将新的键值对添加到 Power shell 中的 JSON 文件。

"JWTToken": {
"SecretKey": "Security Key For Generate Token",
"Issuer": "ABC Company"
},
"AllowedHosts": "*",
"ModulesConfiguration": {
"AppModules": [ "ABC Modules" ]
},
"ConnectionStrings": {
"DatabaseConnection": "Server=testserver,1433;Database=TestDatabase;User Id=code-developer;password=xyz;Trusted_Connection=False;MultipleActiveResultSets=true;",
"TableStorageConnection": "etc",
"BlobStorageConnection": "etc"
},

使用 PowerShell 将 JSON 字符串转换为对象后,更改属性并不是真正的问题。您将在这里面临的主要问题是您的字符串当前对 .Net 无效,或者至少它不会期望它采用当前格式。不过,我们可以解决这个问题。

这是您当前的 JSON。

"JWTToken": {
"SecretKey": "Security Key For Generate Token",
"Issuer": "ABC Company"
},
"AllowedHosts": "*",
"ModulesConfiguration": {
"AppModules": [ "ABC Modules" ]
},
"ConnectionStrings": {
"DatabaseConnection": "Server=testserver,1433;Database=TestDatabase;User Id=code-developer;password=xyz;Trusted_Connection=False;MultipleActiveResultSets=true;",
"TableStorageConnection": "etc",
"BlobStorageConnection": "etc"
},

对于 PowerShell JSON,在您的application.config文件中可能还有其他问题,但这两个问题对我来说是立即注意到的。

  • 不必要的尾随逗号
  • 没有明确的开盘{和收盘}

我们如何解决这个问题?

我们可以使用简单的字符串连接来添加{并在必要时添加}

$RawText = Get-Content -Path .path_toapplication.config -Raw
$RawText = "{ " + $RawText + " }"

为了在使用 JSON 解析 JSON 时消除任何不必要的尾随逗号解析问题ConvertFrom-Json我们需要通过正则表达式删除它们。我建议的方法是通过当前数组是}还是]在它们之后关闭来识别它们,可能是这些右括号在出现之前有许多空格或s。所以我们会有一个看起来像这样的正则表达式:

",(?=s*?[}]])".

然后,我们可以将其与PowerShell中的-replace一起使用。当然,我们会用空字符串替换它们。

$FormattedText = $RawText -replace ",(?=s*?[}]])",""

从这里我们转换为 JSON。

$JsonObj = $FormattedText | ConvertFrom-Json

现在,我们可以通过设置属性来更改数据库字符串。

$JsonObj.ConnectionStrings.DatabaseConnection = "your new string"

我们使用ConvertTo-Json将数组转换回 Json 字符串。

$JsonString = $JsonObj | ConvertTo-Json

返回尾随逗号并不重要,它们不是有效的 JSON,但您的文件需要删除第一个{和最后一个},然后我们才能将其提交回带有Set-Content的文件。

# Remove the first { and trim white space. Second TrimStart() clears the space.
$JsonString = $JsonString.TrimStart("{").TrimStart()
# Repeat this but for the final } and use TrimEnd().
$JsonString = $JsonString.TrimEnd("}").TrimEnd()
# Write back to file.
$JsonString | Set-Content -Path .path_toapplication.config -Force

您的配置文件应该或多或少地写回您找到它。我会尝试想一个正则表达式来修复格式的外观,它不应该出错,只是看起来不太好。希望有帮助。

编辑

这是一个修复文件中文本难看外观的功能。

function  Restore-Formatting {
Param (
[parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$InputObject
)  
$JsonArray = $InputObject -split "n"
$Tab = 0
$Output = @()
foreach ($Line in $JsonArray) {
if ($Line -match "{" -or $Line -match "[") { 
$Output += (" " * $Tab) + $Line.TrimStart()
$Tab += 4 
}
elseif ($Line -match "^s+}" -or $Line -match "^s+]") {
$Tab -= 4
$Output += (" " * $Tab) + $Line.TrimStart()
}
else {
$Output += (" " * $Tab) + $Line.TrimStart()
}
}
$Output
}

TL;灾难恢复脚本:

$RawText = Get-Content -Path .path_toapplication.config -Raw
$RawText = "{ " + $RawText + " }"
$FormattedText = $RawText -replace ",(?=s*?[}]])",""
$JsonObj = $FormattedText | ConvertFrom-Json
$JsonObj.ConnectionStrings.DatabaseConnection = "your new string"
$JsonString = $JsonObj | ConvertTo-Json
$JsonString = $JsonString.TrimStart("{").TrimStart()
$JsonString = $JsonString.TrimEnd("}").TrimEnd()
$JsonString | Restore-Formatting | Set-Content -Path .path_toapplication.config -NoNewLine -Force