Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON string in JavaScript?

window.onload = function(){     var obj = '{             "name" : "Raj",             "age"  : 32,             "married" : false             }';      var val = eval('(' + obj + ')');     alert( "name : " + val.name + "\n" +            "age  : " + val.age  + "\n" +            "married : " + val.married );  } 

In a code something like this, I am trying to create JSON string just to play around. It's throwing error, but if I put all the name, age, married in one single line (line 2) it doesn't. Whats the problem?

like image 709
indianwebdevil Avatar asked Jan 22 '12 18:01

indianwebdevil


People also ask

How do I create a JSON string?

married = false; //convert object to json string var string = JSON. stringify(obj); //convert string to Json Object console. log(JSON. parse(string)); // this is your requirement.

What is JSON string JavaScript?

The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Can you create JSON file in JavaScript?

Writing to a JSON file: We can write data into a JSON file by using the node. js fs module. We can use writeFile method to write data into a file.


2 Answers

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.

like image 77
Akhil Sekharan Avatar answered Oct 21 '22 08:10

Akhil Sekharan


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,            }`; 
like image 20
bardiir Avatar answered Oct 21 '22 08:10

bardiir