Problem Statement
What does JSON.stringify() do?
Explanation
JSON stringify converts a JavaScript object into a JSON string.
It is used to send data to servers, store data in local storage, or create deep copies.
Undefined, functions, and symbols are omitted from the output. Dates are converted to strings.
You can pass optional parameters for formatting and filtering.
JSON parse does the opposite, converting JSON string back to object.
Code Solution
SolutionRead Only
const obj = {
name: 'John',
age: 30,
active: true
};
// Convert to JSON string
const json = JSON.stringify(obj);
console.log(json); // '{"name":"John","age":30,"active":true}'
console.log(typeof json); // 'string'
// Pretty print with indentation
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty);
// {
// "name": "John",
// "age": 30,
// "active": true
// }
// Convert back to object
const parsed = JSON.parse(json);
console.log(parsed); // {name: 'John', age: 30, active: true}
// What gets omitted
const complex = {
name: 'John',
age: 30,
greet: function() {}, // Functions omitted
data: undefined, // undefined omitted
id: Symbol('id') // Symbols omitted
};
console.log(JSON.stringify(complex)); // '{"name":"John","age":30}'
// Deep clone using JSON
const original = {a: 1, b: {c: 2}};
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 3;
console.log(original.b.c); // 2 (unchanged)Practice Sets
This question appears in the following practice sets:
