3 min read
•Question 43 of 50easyHow do JSON.parse and JSON.stringify work?
Understanding JSON serialization.
What You'll Learn
- Converting to/from JSON
- Common pitfalls
- Reviver and replacer functions
JSON.stringify
Converts JavaScript values to JSON strings.
code.jsJavaScript
const obj = { name: 'John', age: 30 };
JSON.stringify(obj); // '{"name":"John","age":30}'
// Pretty print
JSON.stringify(obj, null, 2);
/*
{
"name": "John",
"age": 30
}
*/
// Filter properties
JSON.stringify(obj, ['name']); // '{"name":"John"}'
// Custom replacer
JSON.stringify(obj, (key, value) => {
if (key === 'age') return undefined;
return value;
}); // '{"name":"John"}'JSON.parse
Converts JSON strings to JavaScript values.
code.jsJavaScript
const json = '{"name":"John","age":30}';
const obj = JSON.parse(json);
// { name: 'John', age: 30 }
// With reviver
JSON.parse(json, (key, value) => {
if (key === 'age') return value + 1;
return value;
}); // { name: 'John', age: 31 }Values Not Supported
code.jsJavaScript
const obj = {
fn: function() {}, // Lost
sym: Symbol('x'), // Lost
undef: undefined, // Lost
date: new Date(), // Becomes string
nan: NaN, // Becomes null
inf: Infinity // Becomes null
};
JSON.parse(JSON.stringify(obj));
// { date: '2024-01-15T...', nan: null, inf: null }Error Handling
code.jsJavaScript
try {
JSON.parse('invalid json');
} catch (e) {
console.error('Parse error:', e.message);
}