Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma separated list into JSON using Javascript

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"}
    ]
  };
like image 848
Mike Mike Avatar asked Dec 07 '22 14:12

Mike Mike


1 Answers

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

like image 199
Esailija Avatar answered Jan 19 '23 12:01

Esailija