Skip to content
jshacks.dev
Functions

Implement JSON.stringify From Scratch in JavaScript

Write JSON.stringify from scratch in JavaScript, with string escaping, nested values, undefined and function rules, toJSON, indentation and cycles. Node.js 24.

8 min read
Summarize in AI
Flat illustration of a model being transformed into JSON, with the JSON, JavaScript, Swagger, Postman and OpenAPI Initiative logos.

JSON.stringify looks like a recursive switch statement, and the first ten minutes of the interview go that way: strings get quotes, numbers become text, arrays and objects recurse. The remaining time goes to the rules that make it surprising. undefined vanishes from objects but becomes null in arrays, NaN becomes null, a Date turns into a string through toJSON, and a cycle throws. This post writes a faithful stringify on Node.js 24, rule by rule, and states each rule so you can defend it. It supports the optional indentation argument, and it ends with tests that compare the result against the built-in. The specification is in ECMAScript, JSON.stringify, and the rules below follow it.

The value rules

The function takes a value and returns a string, or undefined when the value cannot be represented. Write the rules for each type in the order the specification checks them.

InputResult
null"null"
true, false"true", "false"
a finite numberits decimal text
NaN, Infinity, -Infinity"null"
a stringquoted and escaped
undefined, a function, a symbolundefined (no result)
an array[ items joined by commas ]
a plain object{ key-value pairs }
a bigintthrows TypeError

Escaping strings

A JSON string is surrounded by double quotes. Inside, the double quote and the backslash are escaped, and control characters below 0x20 must be escaped too, using the short forms where they exist.

JavaScript
const SHORT = { '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t" };

function quote(text) {
  return (
    '"' +
    text.replace(/["\\\u0000-\u001f]/g, (char) => {
      return SHORT[char] ?? "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0");
    }) +
    '"'
  );
}

console.log(quote('say "hi"\n'));
console.log(quote("tab\there"));
console.log(quote("\u0001"));
Text
"say \"hi\"\n"
"tab\there"
"\u0001"

The regular expression matches the quote, the backslash and every character from U+0000 to U+001F. Characters with a short escape use it, and the rest use a four-digit \u escape, with the hex padded to four digits. The output above is the quoted text printed as is, so the \n is the two characters backslash and n, not a line break.

One more rule in modern engines: since ES2019 (the "well-formed JSON.stringify" change), a lone surrogate, half of an emoji that lost its partner, is written as a \uXXXX escape instead of being output raw, so the result is always valid Unicode. Handle it if you want the exact built-in behavior.

JavaScript
function quote(text) {
  return (
    '"' +
    text
      .replace(/["\\\u0000-\u001f]/g, (char) => {
        return SHORT[char] ?? "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0");
      })
      .replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, (char) => {
        return "\\u" + char.charCodeAt(0).toString(16);
      }) +
    '"'
  );
}

console.log(quote("\ud83d"));
console.log(quote("šŸ˜€"));
Text
"\ud83d"
"šŸ˜€"

The second replace finds a high surrogate that is not followed by a low one, or a low surrogate not preceded by a high one. A proper pair, as in the emoji, is untouched.

The core function

JavaScript
function stringify(value) {
  if (value === null) return "null";

  if (typeof value === "boolean") return String(value);

  if (typeof value === "number") {
    return Number.isFinite(value) ? String(value) : "null";
  }

  if (typeof value === "string") return quote(value);

  if (typeof value === "bigint") {
    throw new TypeError("Do not know how to serialize a BigInt");
  }

  if (value === undefined || typeof value === "function" || typeof value === "symbol") {
    return undefined;
  }

  if (Array.isArray(value)) {
    const items = value.map((item) => stringify(item) ?? "null");
    return "[" + items.join(",") + "]";
  }

  const pairs = [];

  for (const key of Object.keys(value)) {
    const text = stringify(value[key]);

    if (text !== undefined) {
      pairs.push(quote(key) + ":" + text);
    }
  }

  return "{" + pairs.join(",") + "}";
}

console.log(stringify({ a: 1, b: [true, null, "x"], c: undefined, d: () => 1 }));
console.log(stringify([undefined, NaN, Infinity, () => 1]));
console.log(stringify("only a string"));
console.log(stringify(undefined));
Text
{"a":1,"b":[true,null,"x"]}
[null,null,null,null]
"only a string"
undefined

The two lines worth studying are the array and the object branch. In an array, an item that cannot be serialized becomes null, because dropping it would shift every index after it. In an object, the pair is left out entirely, because a missing key is a faithful way to say "no value". Both choices follow from keeping the shape meaningful. And the top-level stringify(undefined) really returns the value undefined, not the string, which is why JSON.stringify(undefined) prints undefined in a console.

Object.keys returns own enumerable string keys in the order the specification defines: integer-like keys first in ascending order, then other keys in insertion order. That is also the order JSON.stringify uses. Symbol keys are skipped by both.

toJSON

If a value has a toJSON method, the result of calling it is serialized in place of the value. That is how Date works.

JavaScript
function prepare(value, key) {
  if (value !== null && typeof value === "object" && typeof value.toJSON === "function") {
    return value.toJSON(key);
  }

  return value;
}

const when = new Date(Date.UTC(2026, 0, 2, 3, 4, 5));

console.log(when.toJSON());
Text
2026-01-02T03:04:05.000Z

Call prepare(value, key) at the top of stringify, passing the property name, or the array index as a string, as the argument. Note the order: toJSON runs before the type checks, because it can return anything, including a string or another object. A class can define toJSON to control its own serialization, and Map and Set have none, which is why JSON.stringify(new Map([[1, 2]])) gives {}: the object has no own enumerable keys.

JavaScript
console.log(stringify(new Map([[1, 2]])));
console.log(stringify(new Set([1, 2])));
Text
{}
{}

These are the answers an interviewer hopes you know, and the reason a "reviver and replacer" pair exists on the built-in.

Indentation

The second feature is the space argument, which pretty-prints. A number means that many spaces per level, and a string means the string itself, in both cases capped at ten characters. Empty arrays and objects stay as [] and {}.

JavaScript
function stringify(value, space = 0, indent = "") {
  const unit = typeof space === "number" ? " ".repeat(Math.min(10, space)) : String(space).slice(0, 10);

  const wrap = (open, close, parts) => {
    if (parts.length === 0) return open + close;
    if (!unit) return open + parts.join(",") + close;

    const inner = indent + unit;
    return open + "\n" + inner + parts.join(",\n" + inner) + "\n" + indent + close;
  };

  value = prepare(value, "");

  if (value === null) return "null";
  if (typeof value === "boolean") return String(value);
  if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
  if (typeof value === "string") return quote(value);
  if (typeof value === "bigint") throw new TypeError("Do not know how to serialize a BigInt");
  if (value === undefined || typeof value === "function" || typeof value === "symbol") return undefined;

  const next = indent + unit;

  if (Array.isArray(value)) {
    return wrap("[", "]", value.map((item, index) => stringify(prepare(item, String(index)), space, next) ?? "null"));
  }

  const pairs = [];

  for (const key of Object.keys(value)) {
    const text = stringify(prepare(value[key], key), space, next);

    if (text !== undefined) {
      pairs.push(quote(key) + (unit ? ": " : ":") + text);
    }
  }

  return wrap("{", "}", pairs);
}

console.log(stringify({ name: "Ada", tags: ["a", "b"], empty: [] }, 2));
Text
{
  "name": "Ada",
  "tags": [
    "a",
    "b"
  ],
  "empty": []
}

The indent argument carries the current depth as a string, so each recursion adds one unit. A colon is followed by a space only when pretty-printing, and empty containers never get line breaks, exactly as in the built-in.

Cycles

An object that contains itself would recurse forever. The built-in throws a TypeError that begins "Converting circular structure to JSON". Track the objects on the current path, and throw when one repeats.

JavaScript
function stringifySafe(value, stack = []) {
  if (value !== null && typeof value === "object") {
    if (stack.includes(value)) {
      throw new TypeError("Converting circular structure to JSON");
    }
    stack = [...stack, value];
  }

  if (Array.isArray(value)) {
    return "[" + value.map((v) => stringifySafe(v, stack) ?? "null").join(",") + "]";
  }

  if (value !== null && typeof value === "object") {
    return (
      "{" +
      Object.keys(value)
        .map((k) => {
          const text = stringifySafe(value[k], stack);
          return text === undefined ? null : quote(k) + ":" + text;
        })
        .filter((pair) => pair !== null)
        .join(",") +
      "}"
    );
  }

  return stringify(value);
}

const loop = { name: "loop" };
loop.self = loop;

try {
  stringifySafe(loop);
} catch (error) {
  console.log(error.name, error.message);
}

const shared = { x: 1 };
console.log(stringifySafe({ a: shared, b: shared }));
Text
TypeError Converting circular structure to JSON
{"a":{"x":1},"b":{"x":1}}

The stack holds only the ancestors of the current value, not every object seen. That distinction matters: the same object appearing twice in different branches, as shared does, is not a cycle and must serialize twice. A global "seen" set would wrongly reject it.

Comparing against the built-in

The best test of a reimplementation is the original, as an oracle.

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

const samples = [
  null,
  true,
  42,
  -0,
  NaN,
  "line\nbreak \"quoted\"",
  [1, undefined, () => 1, "x"],
  { a: undefined, b: { c: [] }, "key with space": 1 },
  new Date(0),
  { 2: "b", 1: "a", z: 0 },
];

test("matches JSON.stringify", () => {
  for (const sample of samples) {
    assert.equal(stringify(sample), JSON.stringify(sample));
  }
});

test("matches with indentation", () => {
  const value = { a: [1, { b: 2 }], c: "d" };
  assert.equal(stringify(value, 4), JSON.stringify(value, null, 4));
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

The sample -0 is there on purpose: String(-0) is "0", and JSON.stringify(-0) is also "0", so the negative zero is lost in both.

Mistakes that show up in real code

Most bugs with JSON.stringify are not in the function. They are in what people expect it to do. Dates survive as strings and come back from JSON.parse as strings, so a round trip changes their type and any comparison that expects a Date quietly fails. A Map or Set becomes {}, which looks like success until the data is gone. A BigInt throws, so an API response that adds a large identifier can start failing in production with no change to the serializing code.

The usual fixes are small. Convert the value before serializing, define toJSON on your own classes, or pass a replacer that handles the types you use. And when a number must keep exact precision beyond what a double holds, send it as a string and say so in the API documentation, because no amount of care in stringify recovers digits that a number cannot store.

What was left out

The built-in also accepts a replacer, a function or an array of allowed keys, and it unwraps boxed primitives such as new Number(1). The replacer is a short addition inside the object loop. Beyond that, performance engines are a different topic: the native version is written in C++ and has fast paths for common shapes, so the point of writing your own is understanding, not replacing it. The newer JSON source text access proposal is about JSON.parse, not stringify.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.