Converting JavaScript values to JSON using stringify

JSON.stringify

 
stringify is used for writing JavaScript values into a valid JSON.
 
Syntax of the JSON stringify Method


JSON.stringify(value[, replacer [, space]]);

Only value is mandatory for stringify method.
 

JSON stringify example

 

<!DOCTYPE html>
<html>
<body>

<h2>
JSON Stringify Example
</h2>
<p id="jsonparsing"></p>

<script>
var employee = new Object();
employee.name = "John";
employee.age = 36;
employee.address = "123 LasVegas Blvd";

var jsonText = JSON.stringify(employee);

document.getElementById("jsonparsing").innerHTML = jsonText;
</body>
</html>


 

 

JSON stringify with replacer

 
A replacer function can be used with stringify to Provide Custom Serializing
 

<!DOCTYPE html>
<html>
<body>

<h2>
JSON Stringify Example
</h2>
<p id="jsonparsing"></p>

<script>
var employee = new Object();
employee.name = "John";
employee.age = 36;
employee.address = "123 LasVegas Blvd";

var jsonText = JSON.stringify(employee,
  function(k, v) {
    if (k === "address") {
      //append string USA at end of address
      v += ", USA";
    }
    return v;
  });

document.getElementById("jsonparsing").innerHTML = jsonText;
</body>
</html>

 

 

JSON stringify with space

 
Optional space parameter allows you to specify the amount of padding between elements within the produced JSON text.
 
For example,

JSON.stringify(obj,null,1) adds padding of 1 space between elements in produced JSON.

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags