4

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"}
    ]
  };
BenMorel
  • 31,815
  • 47
  • 169
  • 296
Mike Mike
  • 1,115
  • 3
  • 13
  • 19

1 Answers1

15
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

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
Esailija
  • 134,577
  • 23
  • 263
  • 318