4

如何使用 Javascript / jQuery 将逗号分隔的列表转换为 json?

例如

转换以下内容:

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

进入:

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

1 回答 1

15
var jsonfied = {
    names: names.replace( /,$/, "" ).split(",").map(function(name) {
        return {name: name};
    })
};

stringfying jsonfied 的结果:

JSON.stringify( jsonfied );

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

现场演示

于 2012-05-04T01:35:33.573 回答