Lesson

JS JSON

10 min reading
Free Course

JavaScript JSON: Serializing and Parsing Data Safely

JavaScript JSON handling comes down to two built-in methods: JSON.stringify() turns a value into JSON text, and JSON.parse() turns JSON text back into a JavaScript value. JSON (JavaScript Object Notation) is a lightweight, language-independent text format that most APIs use to exchange structured data.

This guide covers JSON's strict syntax, how serialization treats different value types, how to parse without crashing your app, and the cloning shortcut that quietly loses data.

JSON Syntax vs. JavaScript Objects

JSON looks like a JavaScript object literal, but its rules are much tighter. The format is defined in RFC 8259 and summarized at json.org.

  • Double quotes are required. Every key and string value must use "double quotes", never single quotes.

  • No trailing commas and no comments. { "a": 1, } and // notes both make JSON.parse() throw.

  • Only a few value types exist. Objects, arrays, strings, numbers, booleans, and null. There is no undefined, function, Date, Map, or Set.

Serialize and Parse JSON in JavaScript Safely

Pass null, 2 to JSON.stringify() for readable two-space indentation, which helps with logs and config files. Wrap JSON.parse() in try...catch, because it throws a SyntaxError on invalid input.

const payload = {
  id: 42,
  tags: ["js", "json"],
  createdAt: new Date("2026-11-12T10:00:00Z"),
  helper: () => "ignored", // omitted by JSON.stringify
};

const jsonText = JSON.stringify(payload, null, 2);
console.log("Serialized JSON:
" + jsonText);

function parseSafely(raw) {
  try {
    return JSON.parse(raw);
  } catch (err) {
    console.error("Invalid JSON:", err.message);
    return null;
  }
}

console.log("Parsed object:", parseSafely(jsonText));

The serialized text contains id, tags, and createdAt as "2026-11-12T10:00:00.000Z". The helper function is gone. The parsed object has the same three properties, and createdAt is a plain string, not a Date. The exact wording of err. message differs between browsers and Node.js, so log it for debugging but don't match on it in code.

How to Check It Worked

Log the result of parseSafely(). If you get null, the input was invalid, and the logged message usually points to the problem character. Pasting suspect text into your browser console with JSON.parse() is a quick way to isolate it.

Common Mistakes with JavaScript JSON

Calling JSON.parse() without try...catch

Any text you don't control can be malformed: an API error page returned as HTML, a truncated response, or a corrupted string in localStorage. One uncaught SyntaxError can break the code that renders your page. Two details help here. JSON.parse(undefined) throws because the text "undefined" is not valid JSON, while localStorage.getItem() returns null for a missing key, and JSON.parse(null) returns null without throwing.

Expecting dates to come back as dates

JSON has no date type, so JSON.parse() gives you the ISO string. Convert it yourself with new Date(obj.createdAt), or use a reviver (see the FAQ).

Cloning with JSON.parse(JSON.stringify(obj))

This trick silently drops undefined properties and functions, turns Date values into strings, flattens Map and Set into empty objects, and throws on BigInt and circular references. Prefer structuredClone(), which preserves dates, maps, sets, and circular references. It has limits too: it throws a DataCloneError on functions, so remove them first.

Forgetting that fetch responses are parsed for you

When you call response.json() on a fetch() result, parsing happens inside the method. A bad body rejects the promise, so handle that with try...catch or .catch(). See our lesson on JavaScript fetch and APIs.

Frequently Asked Questions

What is a reviver function in JSON.parse()?

It is an optional second argument, (key, value) => ..., that transforms each value as it is parsed. It is a clean way to turn timestamp strings back into dates:

Why does JSON.stringify({ x: undefined }) return "{}"?

JSON has no undefined type, so the property is omitted. Inside arrays, undefined becomes null to keep the positions intact.

What is the difference between JSON and a JavaScript object?

A JavaScript object is a live value in memory and can hold functions, dates, and more. JSON is text with a strict syntax that represents a limited set of types.

Is JSON.parse() safe to use on untrusted input?

It does not execute code, unlike eval(), so it is the correct tool. Still, validate the shape of the result before trusting its fields.

Conclusion

Treat JSON as a strict text format, not a copy of your objects. Know what stringify() drops, guard every parse() with error handling, convert dates deliberately, and use structuredClone() for deep copies. Next, learn how JavaScript objects work, or read MDN's overview of working with JSON.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum