🌱BeginnerData & APIs
JSON
JSON.stringify and JSON.parse the universal format for data exchange in web applications.
Overview
**JSON** (JavaScript Object Notation) is a text format for representing structured data. It's the universal language of web APIs when your frontend talks to a backend, both sides almost certainly send and receive JSON.
JSON looks like JavaScript objects and arrays, but it's just a string with strict rules: keys must be in double quotes, values can be strings (double-quoted), numbers, booleans, arrays, objects, or `null`. Functions, `undefined`, and Symbols are not valid JSON.
`JSON.stringify(value)` converts a JavaScript value to a JSON string. `JSON.parse(text)` converts a JSON string back into a JavaScript value. Both can throw, so wrap them in `try/catch` when handling external data.
A useful trick: `JSON.parse(JSON.stringify(obj))` creates a deep clone of a plain object every nested value is duplicated, not shared.
Key Points
- •`JSON.stringify(value)` JS value → JSON string
- •`JSON.parse(text)` JSON string → JS value; throws `SyntaxError` on invalid JSON
- •JSON keys must be double-quoted strings; values: string, number, boolean, array, object, or null
- •`undefined`, functions, and Symbols are stripped by `stringify` (or become `null` inside arrays)
- •`JSON.stringify(value, null, 2)` pretty-prints with 2-space indent
- •`JSON.stringify(value, replacer)` filter which keys to include
- •`JSON.parse(text, reviver)` transform values during parsing (e.g. convert date strings)
- •`JSON.parse(JSON.stringify(obj))` simple deep clone of plain objects (loses prototypes and special types)
Examples
stringify and parse basics
const user = {
name: "Alice",
age: 30,
scores: [95, 87, 92],
active: true,
address: { city: "London" }
};
// Object → JSON string
const json = JSON.stringify(user);
console.log(json);
// '{"name":"Alice","age":30,"scores":[95,87,92],"active":true,"address":{"city":"London"}}'
// JSON string → object
const parsed = JSON.parse(json);
console.log(parsed.name); // "Alice"
console.log(parsed.address.city); // "London"
console.log(parsed.scores[1]); // 87
// Pretty-print
console.log(JSON.stringify(user, null, 2));What gets stripped and safe parsing
const obj = {
name: "Bob",
fn: () => "hello", // function stripped
sym: Symbol("id"), // Symbol stripped
val: undefined, // undefined stripped
score: null, // null kept
};
const json = JSON.stringify(obj);
console.log(json); // '{"name":"Bob","score":null}'
// Always parse with try/catch when data comes from outside
function safeParseJSON(str) {
try {
return JSON.parse(str);
} catch {
return null;
}
}
console.log(safeParseJSON('{"valid":true}')); // {valid: true}
console.log(safeParseJSON("not json")); // nullDeep clone and practical API usage
// Deep clone via JSON round-trip
const original = { a: 1, nested: { b: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.nested.b = 99;
console.log(original.nested.b); // 2 (unaffected)
// Simulated API response handling
const apiResponse = `{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
],
"total": 2
}`;
const data = JSON.parse(apiResponse);
data.users.forEach(u => console.log(`${u.id}: ${u.name}`));Common Mistakes
- Using single quotes in JSON JSON requires double quotes for all strings and keys
- Not using try/catch around JSON.parse it throws SyntaxError for any malformed input
- Assuming JSON.parse/stringify preserves all JS types Date objects become strings, Maps/Sets become {}, functions disappear
Note
When debugging API responses, use `console.log(JSON.stringify(data, null, 2))` to get a nicely formatted, readable view of any object in the console.
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4