Need to convert comma separated string into json string

Viewed 98

I will get email id's as comma separated string (recipient1@example.com,recipient2@example.com,recipient3@example.com ). How can I build json string like this by using power shell

{"personalizations": [
{"to": [
    {"email": "recipient1@example.com"},
    {"email": "recipient2@example.com"}
]}]}
1 Answers

Split input string with the String.Split() method, then construct an object that looks like the desired JSON and finally pipe through ConvertTo-Json:

$recipients = "recipient1@example.com,recipient2@example.com,recipient3@example.com"

@{
  personalizations = @(
    @{
      to = @(
        $recipients.Split(',').ForEach({@{email=$_}})
      )
    }
  )
} |ConvertTo-Json -Depth 4
Related