Introduction
Working with JSON in JavaScript is built directly into the language specification via the global JSON object.
1. JSON.parse() - Parsing Strings to Objects
When fetching data from API endpoints, use JSON.parse():
const rawResponse = '{"id": 42, "title": "Web Development"}';
try {
const data = JSON.parse(rawResponse);
console.log(data.title);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
2. JSON.stringify() - Object to JSON String
Convert objects to formatted JSON strings:
const settings = { theme: 'dark', notifications: true };
const formattedJSON = JSON.stringify(settings, null, 2);
console.log(formattedJSON);
3. Deep Cloning Objects with structuredClone
Modern JavaScript supports native deep cloning without JSON.parse(JSON.stringify()):
const original = { a: 1, b: { c: 2 } };
const copy = structuredClone(original);
Format and validate your JSON payloads securely with JSON Workshop.