JSON.parse
Converts valid JSON text into JavaScript data.
JSON.parse turns JSON text into data. JSON.stringify turns data into JSON text.
const data = { title: "Dashboard", active: true };
const json = JSON.stringify(data, null, 2);
console.log(json);
JSON & Structured Data
Use JSON.parse when data arrives as a JSON string. Use JSON.stringify when you need to send or store structured data as text.
JSON.stringify skips undefined properties and functions. Date objects become ISO strings because Date defines a JSON conversion behavior.
The second and third arguments of stringify can filter and format output. The third argument is useful for readable logs and files.
Converts valid JSON text into JavaScript data.
Converts serializable data into JSON text.
Filters or transforms values while stringifying.
Pretty-prints JSON with indentation.
Examples
try {
const data = JSON.parse(rawJson);
console.log(JSON.stringify(data, null, 2));
} catch (error) {
console.error("Could not parse JSON");
}
const data = JSON.parse(rawJson); // One invalid character can stop the script.
Code patterns
These patterns focus on the data boundaries you will use constantly: JSON, URLs, forms, files, fetch objects and binary buffers.
Use try/catch around external JSON.
try {
const data = JSON.parse(json);
console.log(data);
} catch (error) {
console.error("Invalid JSON");
}
Compact JSON is good for APIs.
const json = JSON.stringify({ title: "Dashboard" });
Readable JSON helps debugging.
const json = JSON.stringify(data, null, 2);
Remove fields while converting.
const json = JSON.stringify(data, (key, value) => {
return key === "internal" ? undefined : value;
});
Rules that matter
Structured data becomes reliable when every boundary is explicit: text to object, form to values, URL to parameters, response to JSON and bytes to meaning.
Invalid JSON throws immediately.
Whitespace is usually unnecessary for API requests.
Indentation makes logs and files readable.
undefined, functions and symbols are not represented as object properties.
Map, Set, BigInt and Date need thought.
Circular references throw a TypeError.
Production thinking
Parsing and stringifying are boundary operations. They should be explicit and protected.
If JSON powers visible content, failed parsing should produce a clear message instead of a broken interface.
Production code should centralize JSON boundary handling so parse errors and missing fields are handled consistently.
JSON-LD must stringify cleanly and remain valid when embedded in HTML.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
Structured data is safe only when you know where it came from, what shape it has and what conversion happened before use.