How to create JSON string in JavaScript?

Solution 1:

The way i do it is:

   var obj = new Object();
   obj.name = "Raj";
   obj.age  = 32;
   obj.married = false;
   var jsonString= JSON.stringify(obj);

I guess this way can reduce chances for errors.

Solution 2:

Disclaimer: This is not an answer to follow for the best way how to create JSON in JavaScript itself. This answer mostly tackles the question of "what is the problem?" or WHY the code above does not work - which is a wrong string concatenation attempt in JavaScript and does not tackle why String concatenation is a very bad way of creating a JSON String in the first place.

See here for best way to create JSON: https://stackoverflow.com/a/13488998/1127761

Read this answer to understand why the code sample above does not work.

Javascript doesn't handle Strings over multiple lines.

You will need to concatenate those:

var obj = '{'
       +'"name" : "Raj",'
       +'"age"  : 32,'
       +'"married" : false'
       +'}';

You can also use template literals in ES6 and above: (See here for the documentation)

var obj = `{
           "name" : "Raj",
           "age" : 32,
           "married" : false,
           }`;