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
  • 34,448
  • 50
  • 182
  • 322
Mike Mike
  • 1,125
  • 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
  • 147,333
  • 58
  • 291
  • 367
Esailija
  • 138,174
  • 23
  • 272
  • 326