How do you convert a ma 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"}
]
};
How do you convert a ma 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"}
]
};
Share
edited Sep 19, 2014 at 23:59
BenMorel
36.7k52 gold badges205 silver badges337 bronze badges
asked May 4, 2012 at 1:16
Mike MikeMike Mike
1,1353 gold badges14 silver badges19 bronze badges
1 Answer
Reset to default 15var 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