Convert comma separated list into JSON using Javascript

Mike Mike picture Mike Mike · May 4, 2012 · Viewed 11.7k times · Source

How do you convert a comma separated list into json using Javascript / jQuery?

e.g.

Convert the following:

var names = "Mark,Matthew,Luke,John,";

into:

var jsonified = {
    names: [
      {name: "Mark"},
      {name: "Mattew"},
      {name: "Luke"},
      {name: "John"}
    ]
  };

Answer

Esailija picture Esailija · May 4, 2012
var jsonfied = {
    names: names.replace( /,$/, "" ).split(",").map(function(name) {
        return {name: name};
    })
};

result of stringfying jsonfied:

JSON.stringify( jsonfied );

{
    "names": [{
        "name": "Mark"
    }, {
        "name": "Matthew"
    }, {
        "name": "Luke"
    }, {
        "name": "John"
    }]
}

Live DEMO