【发布时间】:2021-02-06 18:44:42
【问题描述】:
我必须将一些数据注入到 json 文件中。我正在使用 powershell 代码,如下所示。这只是从我的脚本中提取的。变量$MwTagsSelected 是一个pscustom 对象数组,如下所示。
$MwTagsSelected 具有三个属性:TagIndex,TagName,TagValue。我通过下面呈现的foreach 循环传递该对象,结果我得到对象数组$FilteredObjectArray。两个对象数组如下所示。我想将$FilteredObjectArray注入json文件,使用代码$jsoncontent.Resources.MaintenanceWindowTarget.Properties.Targets = $FilteredObjectArray
$MwTagsSelected:
$FilteredObjectArray
我的 powershell 代码:
# get JSON file content
$filename = "inputfile.json"
$content = Get-Content -Path .\$filename
$jsoncontent = $content | ConvertFrom-Json
# JSON file input preparation
$Keys = ($MwTagsSelected | Select-Object -Property TagName -unique).TagName
$FilteredObjectArray = @()
$NotAllowedSelections = @()
$Value = @()
foreach ($Key in $Keys) {
$Value += $MwTagsSelected | Where-Object -FilterScript {$_.TagName -eq $Key}
$FilteredObject = [pscustomobject][ordered] @{
Key = "tag:$Key"
Values = $Value.TagValue
}
if ($Value.Count -gt 5) {
$NotAllowedSelections += $Key
}
$FilteredObjectArray += $FilteredObject
$Value = @()
}
$jsoncontent.Resources.MaintenanceWindowTarget.Properties.Targets = $FilteredObjectArray
$jsoncontent |
ConvertTo-Json -Depth 15 |
Set-Content .\test.json
作为该脚本的输出,我正在获取 json 文件,但 json 结构与预期不符,下面从我的输出 test.json 文件中提取。
"Targets": [
{
"Key": "tag:win",
"Values": [
"01",
"02"
]
},
{
"Key": "tag:ein",
"Values": "03"
}
],
输出 test.json 文件应如下所示:
"Targets": [
{
"Key": "tag:win",
"Values": [
"01",
"02"
]
},
{
"Key": "tag:ein",
"Values": [
"03"
]
}
],
【问题讨论】:
标签: json powershell amazon-cloudformation