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 Answer 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"
}]
}
Sign up to request clarification or add additional context in comments.
1 Comment
gdoron
Added a demo to your answer, I hope you like it, you can rollback if you don't.
lang-js