从Powershell哈希表创建JSON(带有子数组)

时间:2018-08-08 19:56:57

标签: json powershell

我有一个属性名称和值的列表,如下所示:

[string[]]$PropertyNames = 'name', 'priority', 'levelStr', 'escalatingChainId', 'supressAlertClear', 'deviceGroups'
[string[]]$PropertyValues = 'Test', '19665999', 'Warn', '3', 'false', 'TestGroup,TestGroup2'

我正在尝试将其转换为JSON,无论与deviceGroups关联的任何值都应视为数组;

Foreach ($property in $PropertyNames) {
    Switch ($property) {
        {$_ -in ("deviceGroups", "devices")} {
            $propertyData.Add($_, @($($PropertyValues[$index])))

            $index++
        }
        default {
            $propertyData.Add($_, $($PropertyValues[$index]))

            $index++
        }
    }
}

这将生成如下所示的JSON:

{
    "name":  "Test",
    "priority":  "19665999",
    "levelStr":  "Warn",
    "escalatingChainId":  3
    "supressAlertClear": "false"
    "deviceGroups":  [
                    "TestGroup, TestGroup2"
                    ],
    ]
}

那是不好的,因为TestGroup和TestGroup2应该放在单独的行上(因为这应该是JSON数组)。 如何将这些字符串转换为有效的JSON(deviceGroups键/值(可以用逗号分隔)必须是数组)?

1 个答案:

答案 0 :(得分:1)

似乎您忘记了拆分字符串:

Foreach ($property in $PropertyNames) {
    Switch ($property) {
        {$_ -in ("deviceGroups", "devices")} {
            $propertyData.Add($_, @($PropertyValues[$index] -split ','))

            $index++
        }
        default {
            $propertyData.Add($_, $($PropertyValues[$index]))

            $index++
        }
    }
}