使用Javascript将逗号分隔列表转换为JSON

时间:2012-05-04 01:16:05

标签: javascript jquery json delimited-text

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

e.g。

转换以下内容:

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

成:

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

1 个答案:

答案 0 :(得分:14)

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"
    }]
}

Live DEMO