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 = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';

What (I think) it needs to be:

[
    {"email": "bigbadwolf@grannysplace.com"},
    {"email": "hungry@hippos.com"},
    {"email": "youtalkin@to.me"}
]

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.

Community
  • 1
  • 1
chocolata
  • 3,258
  • 5
  • 31
  • 60
  • 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. – Pointy Aug 30 '13 at 14:07

4 Answers4

20
var json = [];
var to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
    json.push({"email":toSplit[i]});
}
Anton
  • 32,245
  • 5
  • 44
  • 54
5

Try this ES6 Version which has better perform code snippet.

'use strict';

let to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';

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

console.log(emailList);
Venkat.R
  • 7,420
  • 5
  • 42
  • 63
4

How about:

var to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me',
    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: "bigbadwolf@grannysplace.com"}
Object {email: "hungry@hippos.com"}
Object {email: "youtalkin@to.me"}

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

tymeJV
  • 103,943
  • 14
  • 161
  • 157
3

Try changing the loop to this:

    var JSON = [];
    $(pieces).each(function(index) {
        JSON.push({'email': pieces[index]});   
    });
Raúl Juárez
  • 2,129
  • 1
  • 19
  • 17