JSON in JavaScript
JavaScript has built-in support for JSON through the JSON global object.
Parsing JSON
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
console.log(obj.age); // 30
Stringifying Objects
const obj = { name: "John", age: 30 };
const json = JSON.stringify(obj);
// '{"name":"John","age":30}'
// Pretty print with indentation
const pretty = JSON.stringify(obj, null, 2);
/
{
"name": "John",
"age": 30
}
/
Handling Errors
function safeParse(jsonString) {
try {
return { data: JSON.parse(jsonString), error: null };
} catch (e) {
return { data: null, error: e.message };
}
}
const { data, error } = safeParse('invalid json');
if (error) {
console.error('Parse error:', error);
}
The Replacer Function
const obj = {
name: "John",
password: "secret",
age: 30
};
// Filter out sensitive data
const json = JSON.stringify(obj, (key, value) => {
if (key === 'password') return undefined;
return value;
});
// '{"name":"John","age":30}'
// Or use an array of allowed keys
JSON.stringify(obj, ['name', 'age']);
// '{"name":"John","age":30}'
The Reviver Function
const json = '{"date": "2024-01-15T00:00:00.000Z"}';
// Convert date strings to Date objects
const obj = JSON.parse(json, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(obj.date instanceof Date); // true
Deep Clone Objects
// Quick deep clone (with limitations)
const clone = JSON.parse(JSON.stringify(original));
// Limitations:
// - Loses functions
// - Loses undefined values
// - Loses Dates (become strings)
// - Loses Map, Set, etc.