JSON.stringify() converts a JavaScript object to a JSON string. This is needed for sending data to server, saving to localStorage, or transferring between parts of application. The method ignores functions, symbols, and undefined.
JSON.stringify() is a method for turning objects into strings. It’s often used when working with server and data storage.
Converts object to JSON format string:
const user = { name: 'John', age: 25 };
const json = JSON.stringify(user);
// Result: '{"name":"John","age":25}'const obj = { a: 1, b: 'text' };
JSON.stringify(obj);
// '{"a":1,"b":"text"}'const arr = [1, 2, 'three'];
JSON.stringify(arr);
// '[1,2,"three"]'const obj = { method: () => {} };
JSON.stringify(obj);
// '{}'const obj = { sym: Symbol('test') };
JSON.stringify(obj);
// '{}'const obj = { value: undefined };
JSON.stringify(obj);
// '{}'const user = { name: 'John', age: 25 };
localStorage.setItem('user', JSON.stringify(user));const data = { message: 'Hello' };
fetch('/api/send', {
method: 'POST',
body: JSON.stringify(data)
});const obj = { name: 'John' };
obj.self = obj; // Circular reference
// JSON.stringify(obj); // Error!const obj = { b: 2, a: 1 };
JSON.stringify(obj);
// '{"b":2,"a":1}' - order preserved// ❌ Think functions will be saved
const config = {
handler: () => console.log('click')
};
const saved = JSON.stringify(config);
// saved = '{}' - function lost!
// ✅ Save only data
const config = {
action: 'click' // action type
};// ❌ Will be error
const obj = { name: 'John' };
obj.parent = obj;
// JSON.stringify(obj); // TypeError
// ✅ Remove circular references before savingJSON.stringify() is a simple way to turn objects into strings for data transfer. Main thing to remember is that not everything can be converted.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪