To send data to a web server or store it in LocalStorage, the data must be a string. JSON.stringify() is a built-in method that converts a JavaScript object or array into a JSON-formatted string.
Observe how a live JavaScript object is converted into a transmission-ready string. Toggle "Pretty Print" to see how whitespace affects readability:
Use JSON.stringify() to convert a JavaScript object into a string:
const user = { name: "Alice", age: 25, city: "Paris" };
const myJSON = JSON.stringify(user);
console.log(myJSON);
// Output: '{"name":"Alice","age":25,"city":"Paris"}'
You can also stringify JavaScript arrays. The result will be a string following JSON array syntax (using square brackets).
const colors = ["Red", "Green", "Blue"];
const myJSON = JSON.stringify(colors);
console.log(myJSON);
// Output: '["Red","Green","Blue"]'
By default, JSON.stringify() removes all whitespace to save space. To make the output human-readable, you can pass a third parameter representing the number of spaces to use for indentation.
// Indent with 4 spaces
let str = JSON.stringify(user, null, 4);
Just like JSON.parse(), stringify has limitations:
JSON.stringify() will automatically convert Date objects into ISO strings.JSON.stringify() will remove functions from a JavaScript object.undefined values are also removed.const obj = {
name: "John",
age: undefined,
greet: function() { return "Hi"; }
};
console.log(JSON.stringify(obj));
// Output: '{"name":"John"}' (age and greet are gone!)