gpt4 book ai didi

json - 使用 Powershell 查找和替换嵌套的 JSON 值

转载 作者:行者123 更新时间:2023-12-02 22:36:08 25 4
gpt4 key购买 nike

我有一个 appsettings.json 文件,我想在 VSTS 发布管道 PowerShell 任务中使用 PowerShell 脚本对其进行转换。 (顺便说一句,我正在将 netstandard 2 Api 部署到 IIS)。 JSON 的结构如下:

{
"Foo": {
"BaseUrl": "http://foo.url.com",
"UrlKey": "12345"
},
"Bar": {
"BaseUrl": "http://bar.url.com"
},
"Blee": {
"BaseUrl": "http://blee.url.com"
}
}

我想替换 BaseUrl,如果它存在,则替换每个部分中的 UrlKey 值,即 Foo、Bar 和 Blee。 (Foo:BaseUrl, Foo:UrlKey, Bar:BaseUrl, 等等)

我正在使用以下 JSON 结构来保存新值:

{ 
"##{FooUrl}":"$(FooUrl)",
"##{FooUrlKey}":"$(FooUrlKey)",
"##{BarUrl}":"$(BarUrl)",
"##{BleeUrl}":"$(BleeUrl)"
}

到目前为止,我有以下脚本:

# Get file path
$filePath = "C:\mywebsite\appsettings.json"

# Parse JSON object from string
$jsonString = "$(MyReplacementVariablesJson)"
$jsonObject = ConvertFrom-Json $jsonString

# Convert JSON replacement variables object to HashTable
$hashTable = @{}
foreach ($property in $jsonObject.PSObject.Properties) {
$hashTable[$property.Name] = $property.Value
}

# Here's where I need some help

# Perform variable replacements
foreach ($key in $hashTable.Keys) {
$sourceFile = Get-Content $filePath
$sourceFile -replace $key, $hashTable[$key] | Set-Content $filePath
Write-Host 'Replaced key' $key 'with value' $hashTable[$key] 'in' $filePath
}

最佳答案

为什么要将替换值定义为 JSON 字符串?那只会让你的生活更悲惨。如果您要在脚本中定义值,请立即将它们定义为哈希表:

$newUrls = @{
'Foo' = 'http://newfoo.example.com'
'Bar' = 'http://newbaz.example.com'
'Blee' = 'http://newblee.example.com'
}

$newKeys = @{
'Foo' = '67890'
}

即使您想从文件中读取它们,您也可以将该文件制作成包含这些哈希表的 PowerShell 脚本并对其进行点源。或者至少将值定义为文本文件中 key=value 行的列表,可以轻松将其转换为哈希表:

$newUrls = Get-Content 'new_urls.txt' | Out-String | ConvertFrom-StringData
$newKeys = Get-Content 'new_keys.txt' | Out-String | ConvertFrom-StringData

然后迭代输入 JSON 数据的顶级属性,并用新值替换嵌套属性:

$json = Get-Content $filePath | Out-String | ConvertFrom-Json
foreach ($name in $json.PSObject.Properties) {
$json.$name.BaseUrl = $newUrls[$name]
if ($newKeys.ContainsKey($name)) {
$json.$name.UrlKey = $newKeys[$name]
}
}
$json | ConvertTo-Json | Set-Content $filePath

请注意,如果您的实际 JSON 数据具有超过 2 层的层次结构,您需要通过参数 -Depth 告诉 ConvertTo-Json 它应该有多少层进行转换。


旁注:需要通过 Out-String 管道传输 Get-Content 输出,因为 ConvertFrom-Json 需要将 JSON 输入作为单个字符串,并使用 Out-String 使代码适用于所有 PowerShell 版本。如果您有 PowerShell v3 或更新版本,您可以通过替换 Get-Content | 来稍微简化代码。带有 Get-Content -Raw 的 Out-String

关于json - 使用 Powershell 查找和替换嵌套的 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com