【发布时间】:2021-01-28 15:37:20
【问题描述】:
我已经准备好Cloud Formation模板,json格式,如下:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"Baseline": {
"Properties": {
"ApprovalRules": {
"PatchRules": [
{
"PatchFilterGroup": {
"PatchFilters": [
{
"Values": [],
"Key": ""
},
{
"Values": [],
"Key": ""
},
{
"Values": [],
"Key": ""
}
]
}
}
]
}
}
}
}
}
我需要将内容注入到那个 json 文件中,所以准备了代码。我需要注入两个数组:Values 和 Key
function ObjectBuilder {
param (
$Values,
$Key
)
$counter = 0
$objecttoinjectArray = @()
foreach ($element1 in $Values) {
$objecttoinject = [pscustomobject][ordered] @{
Values = $element1
Key = $Key[$counter]
}
$objecttoinjectArray += $objecttoinject
$counter++
}
return $objecttoinjectArray
}
$filename = "Matrix.json"
$content = Get-Content -Path .\$filename
$jsoncontent = $content | ConvertFrom-Json
$jsonbuild = $jsoncontent.Resources.Baseline.Properties
$Values = @("BMW, Audi", "Fiat, Ferrari, Porsche, Toyota", "*")
$Key = @("Standard","High","Premium")
$objecttoinjectArray = ObjectBuilder -Values $Values -Key $Key
$jsonbuild.ApprovalRules.PatchRules.PatchFilterGroup.PatchFilters = $objecttoinjectArray
$jsoncontent |
ConvertTo-Json -Depth 15 |
Set-Content .\tests.json
作为输出,我可以看到格式不正确的 json 文件,如下所示:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"Baseline": {
"Properties": {
"ApprovalRules": {
"PatchRules": [
{
"PatchFilterGroup": {
"PatchFilters": [
{
"Values": "BMW, Audi",
"Key": "Standard"
},
{
"Values": "Fiat, Ferrari, Porsche, Toyota",
"Key": "High"
},
{
"Values": "*",
"Key": "Premium"
}
]
}
}
]
}
}
}
}
}
正确的结构应如下所示,AWS cloudformation 不接受该结构:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"Baseline": {
"Properties": {
"ApprovalRules": {
"PatchRules": [
{
"PatchFilterGroup": {
"PatchFilters": [
{
"Values": [
"BMW",
"Audi"
],
"Key": "Standard"
},
{
"Values": [
"Fiat",
"Ferrari",
"Porsche",
"Toyota"
],
"Key": "High"
},
{
"Values": [
"*"
],
"Key": "Premium"
}
]
}
}
]
}
}
}
}
}
【问题讨论】:
-
专业提示:您应该始终在函数中使用适当的缩进,这将使您的代码对您和其他人更具可读性和可维护性。
标签: json powershell amazon-cloudformation