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

问题描述 投票:0回答:1

如何使用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个回答
0
投票

一旦使用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时消除尾随逗号引起的任何不必要的解析问题,我们需要通过正则表达式将其删除。我建议的方法是通过在它们之后的当前数组ConvertFrom-Json}闭合来标识它们,可能是这些闭合括号在出现之前有多个空格或]。因此,我们将得到一个如下所示的正则表达式:

\s

然后我们可以在PowerShell中将其与"\,(?=\s*?[\}\]])"一起使用。当然,我们将它们替换为空字符串。

-replace

从这里我们转换为JSON。

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

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

$JsonObj = $FormattedText | ConvertFrom-Json

我们使用$JsonObj.ConnectionStrings.DatabaseConnection = "your new string" 将数组转换回Json字符串。

ConvertTo-Json

返回尾随的逗号并不重要,它们不是有效的JSON,但是在我们使用ConvertTo-Json将其提交回文件之前,您的文件需要删除第一个$JsonString = $JsonObj | ConvertTo-Json 和最后一个{

}

您发现的配置文件应该或多或少被写回。希望有帮助。

TL; DR脚本:

Set-Content
© www.soinside.com 2019 - 2024. All rights reserved.