【发布时间】:2017-11-13 22:46:52
【问题描述】:
如何将 JSON 文件中的值替换为从配置文件 (JSON) 中获取的另一个值? 这是 JSON 文件的代码:
Config.json
{
"ABlob_AAD_Snapshot": [
{
"name": "properties.availability.frequency",
"value": "$Frequency$"
}]
}
ABlob_AAD_Snapshot.json
{
"name": "AzureBlobStore",
"properties": {
"type": "AzureStorage",
"availability": {
"frequency": "Value from Config.json file"
}
}
}
我想要做的是:
- 浏览 Config.json 文件并将“名称”和“值”段的值存储在变量中。 “名称”段值是 ABlob_AAD_Snapshot.json 文件中的路径。
- 按照 ABlob_AAD_Snapshot.json 文件中的路径,将段“频率”替换为段“值”的值 (
$frequency$)
完成此过程后,ABlob_AAD_Snapshot.json 应如下所示:
{
"name": "AzureBlobStore",
"properties": {
"type": "AzureStorage",
"availability": {
"frequency": "$frequency$"
}
}
}
这里的问题是我的原始 config.json 文件有多个数组(代表文件名),所以我将解析多个文件,并且“名称”段的值并不总是相同,我的意思是,在这种情况下,值(或路径)是properties.availability.frequency,但也可以是properties.activities.scheduler.interval 或properties.activities.typeProperties.extendedProperties.WebAppClientID。
如您所见,“节点”的名称和数量可能会发生变化。
这是我的 PowerShell 脚本:
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
#path to config file
$ConfigFile = "$ScriptPath\ParameterConfigOriginal.json"
#Convert the json file to PSObject
$json = Get-Content $ConfigFile | Out-String | ConvertFrom-Json
#Get all the arrays (files) in Conifg.json
$files = $json | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name
#Go through all the arrays (files)
Foreach($file in $files)
{
if( $file -eq '$schema') {continue}
#store the path of the file to be modified
$FileName = $file + ".json"
$FilePath = "$ScriptPath\LinkedServices\" + $FileName"
#Go through all the elements of the arrray
Foreach($item in $json.$file)
{
#Store the path
$name = $item.name
#Store the value
$value = $item.value
#Convert the file to be modified to PSObject
$file = Get-Content $FilePath | Out-String | ConvertFrom-Json
#======STUCK IN HERE=============
# How can dynamically navigate through the file nodes like this?
$file.properties.availability.frequency
#and set the corresponding value
$file.properties.availability.frequency = $value
}
}
我是 PowerShell 领域的新手,我不知道是否有 cmdlet 可以帮助我做我需要的事情。
任何建议将不胜感激。
编辑
简单路径
$snapshot.properties.availability.frequency
数组路径
$snapshot.properties.activities[0].scheduler.frequency
这是一个带有数组的 JSON 文件示例 Destination file
这就是结果 Destination file updated
知道会发生什么吗?
【问题讨论】:
标签: json powershell powershell-cmdlet