如何使用Javascript / jQuery将逗号分隔列表转换为json?
e.g。
转换以下内容:
var names = "Mark,Matthew,Luke,John,";
成:
var jsonified = {
names: [
{name: "Mark"},
{name: "Mattew"},
{name: "Luke"},
{name: "John"}
]
};
答案 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"
}]
}