【问题标题】:Powershell: Modify key value pair in JSON filePowershell:修改JSON文件中的键值对
【发布时间】:2020-09-07 06:34:02
【问题描述】:

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

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

试图利用这个答案,

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

Add new key value pair to JSON file in powershell.

  "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"
  },

【问题讨论】:

    标签: json powershell scripting appsettings


    【解决方案1】:

    使用 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 + " }"
    

    要在使用ConvertFrom-Json 解析 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_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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      相关资源
      最近更新 更多