Users Online

· Guests Online: 28

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

JSON.stringify JavaScript

JSON.stringify JavaScript

JSON.stringify JavaScript

Introduction to JSON.stringify JavaScript

JSON is JavaScript Object Notation for structuring data. It is a format for storing and transporting data in the form of key-value pairs. JSON.stringify is a method in JavaScript which converts JS Object or a value to JSON String. While developing many applications using JavaScript, data needs to be serialized to strings for storing data in database and sending to API’s. This conversion of object to string can be done with the help of JSON.stringify() method.

Syntax:

JSON.stringify(value, replace, space)

Parameters:

  • value: It is the value which has to be converted into JSON string.
  • replacer: An optional function that can alter the process of stringification. All properties of object are included in resulting string if value is NULL or not provided.
  • space: An optional parameter used to control spacing in final string which is generated using JSON.stringify(). Specified number of spaces will be indented to final string if it is a number and if it is a string, then string up to 10 characters is used for indentation.

Returns a JSON string and throws TypeError exception if circular reference and also when trying to stringify a BigInt type value.

Example:

console.log( JSON.stringify({ x: 32, y: 43 }) );    // returns {"x":32,"y":43}
console.log ( JSON.stringify({ x: 52, y: 0 }, null) );    //returns { "x": 52, "y": 0 }

JSON supports below datatypes

  • Objects{ }
  • Arrays[ ]
  • Primitives such as string, numbers, Boolean value i.e. true or false and NULL

Examples of JSON.stringify JavaScript

Given below are the examples mentioned:

Example #1

Code:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<body>
<script>
var json = {"name": "Saideep","employeeID": 7630};
data = JSON.stringify(json);
document.write('type of data is '+ typeof data + '</br>');
document.write(data);
</script>
</body>
</html>

Output:

JSON.stringify JavaScript 1

Example #2

Code:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<body>
<script>
document.write(JSON.stringify('eduCBA'));
document.write('</br>');
document.write(JSON.stringify({ x: 53 }));
document.write('</br>');
document.write(JSON.stringify(false));
document.write('</br>');
document.write(JSON.stringify({}));
document.write('</br>');
document.write(JSON.stringify([1, 'true', false]));
document.write('</br>');
document.write(JSON.stringify([null, NaN, Infinity]));
document.write('</br>');
document.write(JSON.stringify(new Date(2020, 4, 1, 10, 57, 54)))
document.write('</br>');
document.write(JSON.stringify({ x: 54, y: 76 }));
document.write('</br>');
document.write(JSON.stringify([new Number(35), new String('true'), new Boolean(false)]));
document.write('</br>');
let x = ['eduCBA', 'content'];
x['example'] = 'quickfix';
document.write(JSON.stringify(x));
document.write('</br>');
document.write(JSON.stringify({ y: [110, undefined, function(){}, Symbol('')] }));
document.write('</br>');
document.write(JSON.stringify({x: 2n}));  //BigInt value cannot be serialized in JSON: TypeError
</script>
</body>
</html>

Output:

JSON.stringify JavaScript 2

JSON.stringify() converts value to JSON notation as below:

  • If values are Boolean, Number, String objects are converted to corresponding values by stringification.
  • If value has to JSON() method, it is the responsibility of which data has to be serialized.
  • If value is Undefined, function, or symbols, they are not valid JSON values. These values are either omitted or changed to NULL.
  • Numbers Infinity, NaN and also value of null, are all considered NULL.
  • All Object instances like Map, Set, WeakSet, and WeakMap only enumerable properties will be serialized.

Example #3

Code:

<!DOCTYPE html>
<html>
<body>
<h1>With <em>replacer</em> Function</h1>
<p id="demo"></p>
<script>
var obj = { "name":"Amar", "age":"24", "city":"Pune"};
var text = JSON.stringify(obj, function (key, value) {
if (key == "city") {
return value.toUpperCase();
} else {
return value;
}
});
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Output:

replacer function

Example #4

Code:

<!DOCTYPE html>
<html>
<body>
<h1>With <em>space</em> Parameter</h1>
<p>For each white space, let us insert 5 space characters</p>
<pre id="demo"></pre>
<script>
var obj = { "name":"Sai", "age":"23", "city":"Chennai"};
var text = JSON.stringify(obj, null, 5);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Output:

with space paramter

Space Parameter

String or Number object used to insert white spaces to output JSON. If it’s a number, it indicates the number of space characters to be used as white space. By default the value is capped at 10, if the value is less than 1, no spaces are included. If object is a string, string itself is used as white space and if no value is provided or null, no space is added to output JSON.

Replacer Parameters

Replacer can be either a function or an array, as a function, replacer takes 2 parameters key and value to be stringified. At first, replacer is called with an empty string representing object to be stringified. Replacer cannot be used to remove values from an array, on returning undefined or a function, NULL is used.

Below are the return values for some of the datatypes:

  • If return value is Number, string which corresponds to that number is used as value for property when added to JSON string.
  • If return value is Stringstring is used as property when added to JSON string.
  • If return value is Boolean, i.e. ‘true’ or ‘false’ are the property values added to JSON string.
  • If return value is NULL, null property is added to JSON string.
  • If return value is an object, it is recursively stringified to JSON string.
  • If return value is undefined, property is not added to JSON string.

Conclusion

Points to summarize include what JSON means, how JSON.stringify() work with some of the example have been illustrated. Some of its exceptions, how space and replacer are used in stringification. JSON being a data format has its own standard and libraries. It supports all plain objects like strings, arrays, Boolean and null. JavaScript has provided JSON.stringify() and JSON.parse() to serialize to JSON and read from JSON by using transforming functions. Any object with toJSON is called by JSON.stringify().

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.74 seconds
10,842,689 unique visits