Skip to content

JSON

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.

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-readable
console.log(pretty);
const parsed = JSON.parse(json);
console.log(parsed.name); // "Alice"
// Sending JSON in a fetch request
await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});

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!
  1. What does JSON.stringify() do with a function property on an object?

    AnswerIt silently omits it β€” functions aren't valid JSON values.
  2. What’s the third argument to JSON.stringify(value, replacer, space) used for?

    AnswerIndentation β€” passing a number (like 2) pretty-prints the output with that many spaces per indent level.
  3. What happens if you call JSON.parse() on invalid JSON text?

    AnswerIt throws a SyntaxError β€” always wrap JSON.parse() in a try/catch when parsing data you don't fully trust (like user input or an external API response).