JSON.parse() and JSON.stringify()

Convert between a JavaScript value and its JSON text representation — the standard way data crosses storage and network boundaries.

                JSON.stringify(value) / JSON.parse(text)
              

Purpose

JSON.stringify converts a JavaScript value into a JSON-formatted string. JSON.parse converts a JSON string back into a JavaScript value. Both are how data crosses a text-only boundary — localStorage, a network request body, a file on disk.

Syntax

const data = { name: 'Ada', active: true };
const json = JSON.stringify(data); // '{"name":"Ada","active":true}'
const restored = JSON.parse(json); // a new object, equal in content, not identity

Behavior notes

  • JSON.stringify drops any property whose value is undefined, a function, or a Symbol from an object entirely; the same values become null inside an array instead of being dropped.
  • NaN and Infinity both stringify to null — JSON has no representation for either.
  • Date objects stringify to an ISO string, but JSON.parse never converts that string back into a Date — it comes back as a plain string, and the caller must re-construct a Date explicitly if needed.
  • JSON.stringify(value, null, 2) (a third space argument) pretty-prints with indentation — useful for debugging output.
  • JSON.parse throws a SyntaxError on malformed input — always expect and handle that when parsing data from an external source like localStorage, since it could be missing, cleared by the user, or corrupted.

Common mistakes

  • Assuming JSON.parse(JSON.stringify(x)) is a safe universal deep-copy — it silently loses functions, undefined values, and Date/Map/Set instances, and throws on circular references. Fine for plain, JSON-safe data; not a general-purpose clone.
  • Calling JSON.parse on stored data without a try/catch — malformed or missing stored JSON will throw rather than return null/undefined.

Runtime notes

JSON.stringify/JSON.parse are standard, identical across every current browser and Node version.

Taught in these lessons