Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Convert string with comma separated values to specific JSON format

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.

like image 973
chocolata Avatar asked Aug 30 '13 14:08

chocolata


People also ask

How do I convert a string to JSON?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.

How Split comma separated Values in jQuery?

By using split() function in we can split string with comma or space etc. based on requirement in jQuery.

How do you convert a string separated by a comma to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


2 Answers

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]});
}
like image 148
Anton Avatar answered Oct 12 '22 20:10

Anton


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);
like image 31
Venkat.R Avatar answered Oct 12 '22 18:10

Venkat.R