Updated March 31, 2023
Introduction to JSON Object to String
Today we shall see how to convert JSON object to String. So what are JSON objects here, with all the clear explanation given in our previous courses, you might have had a good idea of these JSON objects and strings? JSON objects are written in key-value pairs, separated by a comma and surrounded by curly braces. JSON objects are used to exchange data to and from a web server. JSON object to String is the conversion of JSON object to Strings which can be achieved by using JSON.stringify() method. While developing many applications using JavaScript, data needs to be serialized to strings for storing data in the database and sending it to API’s.
Syntax
Below is the syntax mentioned:
JSON.stringify(value, replace, space)
There are 3 Parameters as such,
- Value: It is the value that has to be converted into JSON string
- Replacer: An optional function that can alter the process of stringification. All properties of objects are included in the resulting string if the value is NULL or not provided.
- Space: An optional parameter used to control spacing in the final string which is generated using JSON.stringify(). The specified number of spaces will be indented to the 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 the circular reference and also when trying to stringify a BigInt type value.
For example,
console.log( JSON.stringify({ x: 34, y: 56 }) ); // returns {"x":34,"y":56}
console.log ( JSON.stringify({ x: 35, y: 0 }, null) ); //returns { "x": 35, "y": 0 }
JSON supports below datatypes,
- Objects{ }
- Arrays[ ]
- Primitives: string, numbers, Boolean value i.e. true or false, and NULL
Examples of JSON Object to String
Here are the following examples mentioned below.
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:
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() converts value to JSON notation as below,
- If values are Boolean, Number, String objects, are converted to corresponding values by stringification
- If value has toJSON() 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 the 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:
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:
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 the object is a string, the 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, the replacer is called with an empty string representing an 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 the value for the property when added to JSON string.
- If return value is String, the string is used as a property when added to the JSON string.
- If return value is Boolean, i.e. ‘true’ or ‘false’ are the property values added to the JSON string.
- If return value is NULL, the 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, the property is not added to the JSON string.
Conclusion
we have seen how JSON to string conversion is done using JSON.stringify() with some of the examples have been illustrated. Some of its exceptions, how space and replacer are used for conversion of JSON objects to String. JSON being a data format has its standard and libraries, it supports all plain objects like strings, arrays, Boolean, and null. Any object with toJSON is called by JSON.stringify().
Recommended Articles
This is a guide to JSON Object to String. Here we discuss the Syntax and Parameters of JSON Object to String and Examples along with the codes and outputs. You may also have a look at the following articles to learn more-