11

I've been losing hours over something that might be trivial:

I've got a list of comma-separated e-mail addresses that I want to convert to a specific JSON format, for use with the Mandrill API (https://mandrillapp.com/api/docs/messages.JSON.html)

My string:

var to = '[email protected],[email protected],[email protected]';

What (I think) it needs to be:

[
    {"email": "[email protected]"},
    {"email": "[email protected]"},
    {"email": "[email protected]"}
]

I've got a JSFiddle in which I almost have it I think: http://jsfiddle.net/5j8Z7/1/

I've been looking into several jQuery plugins, amongst which: http://code.google.com/p/jquery-json But I keep getting syntax errors.

Another post on SO suggested doing it by hand: JavaScript associative array to JSON

This might be a trivial question, but the Codecadamy documentation of the Mandrill API has been down for some time and there are no decent examples available.

1
  • You could just split it on commas, but if you have no control over the email addresses that's not 100% safe, since a valid email address may have a comma in it. Commented Aug 30, 2013 at 14:07

4 Answers 4

20
var json = [];
var to = '[email protected],[email protected],[email protected]';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
    json.push({"email":toSplit[i]});
}
Sign up to request clarification or add additional context in comments.

1 Comment

You make it look so easy :-) I'll be accepting your answer shortly. I have to wait 10 mins apparently!
5

Try this ES6 Version which has better perform code snippet.

'use strict';

let to = '[email protected],[email protected],[email protected]';

let emailList = to.split(',').map(values => {
    return {
        email: values.trim(),
    }
});

console.log(emailList);

Comments

4

How about:

var to = '[email protected],[email protected],[email protected]',
    obj = [],
    parts = to.split(",");

for (var i = 0; i < parts.length; i++) {
    obj.push({email:parts[i]});
}

//Logging
for (var i = 0; i < obj.length; i++) {
    console.log(obj[i]);
}

Output:

Object {email: "[email protected]"}
Object {email: "[email protected]"}
Object {email: "[email protected]"}

Demo: http://jsfiddle.net/tymeJV/yKPDc/1/

1 Comment

Wow, what a strange technique. Haven't seen this before!
3

Try changing the loop to this:

    var JSON = [];
    $(pieces).each(function(index) {
        JSON.push({'email': pieces[index]});   
    });

1 Comment

Thanks for your answer! I would have accepted it, but @Anton was first ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.