Convert comma separated list into JSON using Javascript

╄→尐↘猪︶ㄣ 提交于 2020-01-21 07:51:26

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/10441458/convert-comma-separated-list-into-json-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!