JSON
What it means
Section titled βWhat it meansβJSON (JavaScript Object Notation) is a text format for representing structured data, used pervasively for APIs and config files. JavaScriptβs built-in JSON object converts between JSON text and JavaScript values: JSON.stringify() turns a JS value into a JSON string, and JSON.parse() turns a JSON string back into a JS value.
Examples
Section titled βExamplesβconst user = { name: "Alice", age: 30, active: true };
const json = JSON.stringify(user);console.log(json); // '{"name":"Alice","age":30,"active":true}'
const pretty = JSON.stringify(user, null, 2); // indented, human-readableconsole.log(pretty);
const parsed = JSON.parse(json);console.log(parsed.name); // "Alice"
// Sending JSON in a fetch requestawait fetch("/api/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(user),});Common mistake
Section titled βCommon mistakeβTrying to JSON.stringify() a value containing things JSON canβt represent β undefined, functions, and Symbol values are silently dropped or converted to null, which can hide bugs where data unexpectedly disappears.
const data = { name: "Alice", greet: function () { return "hi"; }, // function -- silently dropped age: undefined, // undefined -- silently dropped score: NaN, // becomes null};
console.log(JSON.stringify(data));// '{"name":"Alice"}' <- greet, age, and score are all gone!Quick practice
Section titled βQuick practiceβ-
What does
JSON.stringify()do with a function property on an object?Answer
It silently omits it β functions aren't valid JSON values. -
Whatβs the third argument to
JSON.stringify(value, replacer, space)used for?Answer
Indentation β passing a number (like2) pretty-prints the output with that many spaces per indent level. -
What happens if you call
JSON.parse()on invalid JSON text?Answer
It throws aSyntaxErrorβ always wrapJSON.parse()in atry/catchwhen parsing data you don't fully trust (like user input or an external API response).