首页 > 解决方案 > Powershell:修改JSON文件中的键值对

问题描述

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

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

试图利用这个答案,

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

将新的键值对添加到 powershell 中的 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"
  },

标签: jsonpowershellscriptingappsettings

解决方案


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

这是您当前的 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_to\application.config -Raw
$RawText = "{ " + $RawText + " }"

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

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

-replace然后我们可以在 PowerShell 中使用它。当然,我们将用空字符串替换它们。

$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_to\application.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;DR 脚本:

$RawText = Get-Content -Path .\path_to\application.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_to\application.config -NoNewLine -Force

推荐阅读