4

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"}
 ]
 };
BenMorel
37.1k53 gold badges208 silver badges339 bronze badges
asked May 4, 2012 at 1:16

1 Answer 1

15
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

gdoron
151k59 gold badges302 silver badges376 bronze badges
answered May 4, 2012 at 1:35
Sign up to request clarification or add additional context in comments.

1 Comment

Added a demo to your answer, I hope you like it, you can rollback if you don't.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.