The JSON stringify() method is used to convert a JavaScript object or value to a JSON (JavaScript Object Notation) string.
Syntax
JSON.stringify(value, replacer, space)
Parameters
- value(required): It is the value to be converted into the JSON string.
- replacer(optioanl): This parameter can be a function that alters the stringification process or an array used as a selective filter. If this parameter is left empty or null, all properties of the object are included in the string.
- space(optional): A String or Number that is used to insert white space (up to a maximum of 10 characters) into the output JSON string for readability purposes.
Return value
Returns a JSON string representing the given value or undefined.
Visual RepresentationExample 1: How to Use JSON stringify() Method
let obj = { name: "David", age: 30, city: "California" };
let jsonString = JSON.stringify(obj);
console.log(jsonString);
Output
{"name":"David","age":30,"city":"California"}
Example 2: How to stringify an Array
let arr = ['Millie Bobby Brown', 'Finn Wolfhard', 'Noah Schnapp'];
let jsonString = JSON.stringify(arr);
console.log(jsonString);
Output
["Millie Bobby Brown","Finn Wolfhard","Noah Schnapp"]
Example 3: Using a replacer function
let obj = {
name: "David",
age: 30,
city: "California", };
let json = JSON.stringify(obj, function(key, value) {
if (key === "city") {
return undefined;
}
return value;
});
console.log(json);
Output
{"name":"David","age":30}
Example 4: Passing a space parameter
let obj = { name: "David", age: 30, city: "California" };
let jsonString = JSON.stringify(obj,null,3);
console.log(jsonString);
Output
{
"name": "David",
"age": 30,
"city": "California"
}
Browser Compatibility
- Chrome 3 and above
- Firefox 3.5 and above
- Microsoft Edge 12 and above
- Opera 10.5 and above
- Safari 4 and above