Beginner LevelJavaScript & TypeScript
What is JSON and how do JSON.stringify() and JSON.parse() work?
❓ Interview Prompt: Explain JSON serialization/deserialization, replacer/reviver functions, and JSON limitations (functions, undefined, circular refs).
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
Key Methods:
•
`JSON.stringify(value, replacer, space)`: Serializes a JS object/array into a JSON string.
•
`JSON.parse(text, reviver)`: Parses a JSON string back into a JS object/array.
Serialization Limitations:
1
undefined, functions, and Symbols are omitted from plain objects, or converted to null in arrays.2
Date objects become ISO strings.3
Circular references throw a
TypeError: Converting circular structure to JSON.Code Implementation Example
javascript
const data = {
name: 'Alice',
age: 28,
created: new Date(),
secret: undefined, // Will be lost!
greet() {} // Will be lost!
};
// 1. Serialization with indentation
const jsonString = JSON.stringify(data, null, 2);
console.log(jsonString);
// Output omits 'secret' and 'greet'!
// 2. Deserialization with reviver to reconstruct Date objects
const parsed = JSON.parse(jsonString, (key, value) => {
if (key === 'created') return new Date(value);
return value;
});
console.log(parsed.created instanceof Date); // true💡JSON serialization loss of undefined/functions and using reviver to restore Date objects.
🎯 Interview Key Takeaway
JSON.stringify converts JS objects to JSON strings (dropping functions/undefined); JSON.parse reconstructs JS values from JSON strings.
#JSON#Serialization#Parsing#Beginner
Back to all JavaScript & TypeScript Questions→