Stringify a JavaScript Object
Imagine we have this object in JavaScript:
var obj = { name: "Krishna", age: 30, city: "New York" };
JSON.stringify()
to convert it into a string.
var myJSON = JSON.stringify(obj);
The result will be a string following the JSON notation.
myJSON
is now a string, and ready to be sent to a server:
var obj = { name: "Krishna", age: 30, city: "New York" }; var myJSON = JSON.stringify(obj); document.getElementById("demo1").innerHTML = myJSON;
Complete Code For Creating JSON String From A JavaScript Object
<!DOCTYPE html> <html> <head> <title>How To Create JSON String From A JavaScript Object</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Create JSON String From A JavaScript Object</h1> </div> <br> <div class="well"> <h2 id="demo1"></h2> <h2 id="demo2"></h2> </div> <script> var obj = { name: "Krishna", age: 30, city: "New York" }; var myJSON = JSON.stringify(obj); document.getElementById("demo1").innerHTML = myJSON; </script> </div> </body> </html>