0

I have a list of property names and values that looks like this:

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

I am trying to turn it into JSON where whatever value is associated with deviceGroups, should be considered an array;

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

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

            $index++
        }
    }
}

This generates JSON that looks like this:

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

That's no good, because TestGroup and TestGroup2 should be on separate lines (since that is supposed to be a JSON array). How do I turn these strings into valid JSON (where deviceGroups key/value (which could be comma-separated) must be an array)?

3
  • Is deviceGroups an array? When I try this it works fine. Commented Aug 8, 2018 at 20:13
  • I edited the original post to better indicate what I'm starting with. Commented Aug 8, 2018 at 20:29
  • I edited the original post again. I'm not getting the deviceGroups on separate lines. They are a single string within the deviceGroups array, which is in correct. Commented Aug 8, 2018 at 21:03

1 Answer 1

1

Seems like you forgot to split the string:

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

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

            $index++
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

And ($PropertyValues[$index] -split ',').Trim() if you want to attempt to handle such cases.
Yup, I ended up with the same. $propertyData.Add($_, @(($($PropertyValues[$index]).Split(","))).Trim()). Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.