Skip to curriculum
Jump to the editor

22.1. Implement JSON.stringify

Hard
Topics

This question is in

22. Serialization
40–70 min

Every request body, every localStorage entry and every log line that holds an object goes through JSON.stringify. It looks simple, but it makes a lot of quiet decisions: a property set to undefined disappears from an object but turns into null in an array, a Date turns into a string, NaN turns into null, and an object that contains itself makes it throw. Rebuilding it is the best way to learn every one of those rules.

Write stringify(value, replacer, space) in stringify.js. It returns the same result as JSON.stringify(value, replacer, space) for every value: the same string, the same undefined, or a TypeError in the same cases.

Signature

JAVASCRIPT
function stringify(value, replacer, space) // returns a string or undefined
  • value: any value.
  • replacer (optional): a function (key, value) that can change each value, or an array of the keys to keep in objects. Anything else is ignored.
  • space (optional): a number of spaces, or a string, used to indent the output.

Requirements

  1. null, true, false, strings and finite numbers are written as JSON. -0 is written as 0. NaN, Infinity and -Infinity become null.
  2. undefined, functions and symbols have no JSON form: at the top level the result is undefined, in an object the property is left out, and in an array the item becomes null.
  3. Objects list their own enumerable string keys, in Object.keys order, with no spaces: {"a":1,"b":[1,2]}. Symbol keys, non-enumerable and inherited properties are skipped. Getters are read.
  4. Arrays write every index from 0 to length - 1, with length read once before the first item (an array that grows or shrinks while it is written still gives that many items); a hole becomes null. Extra properties on an array are ignored.
  5. Strings and keys are quoted. " and \ are escaped; \b \f \n \r \t use their short forms; other characters below U+0020 become \u00XX (lower-case hex); a lone surrogate becomes \udXXX; everything else, including emoji, is kept as it is.
  6. Number, String and Boolean objects are written as the primitive they hold. A Boolean object's own valueOf does not change that.
  7. When a value (an object, including a function, or a bigint) has a toJSON method, its result is written instead. toJSON is called with the value as this and the property key as its argument ("" at the top level, "0", "1"… in arrays). Dates are written this way.
  8. A bigint throws a TypeError, unless a toJSON turns it into something else.
  9. An object or array that contains itself, at any depth, throws a TypeError. The same object appearing twice side by side is not a cycle and is written twice.
  10. A replacer function is called for every value, after toJSON, with the containing object as this: first with key "" on a wrapper object { "": value }, then for every member. Its return value is written instead; undefined leaves an object member out.
  11. A replacer array lists the keys to write in every object, in its order. Its strings and numbers (and String or Number objects) are used, each once; other items are ignored. Arrays still write every index.
  12. space as a number gives that many spaces per level (rounded down, at most 10; below 1 means none). As a string, its first 10 characters are used. Number and String objects are unwrapped first. With a non-empty indent, every member goes on its own line, : is followed by one space, and empty objects and arrays stay {} and [].

Examples

JAVASCRIPT
stringify({ a: undefined, b: () => 1, c: [undefined, NaN], d: new Date(0) });
// '{"c":[null,null],"d":"1970-01-01T00:00:00.000Z"}'
JAVASCRIPT
stringify('line\nbreak "quoted"');   // '"line\\nbreak \\"quoted\\""'
stringify(undefined);                // undefined
stringify(10n);                      // throws TypeError
JAVASCRIPT
const node = { name: "root" };
node.self = node;
stringify(node);   // throws TypeError

const shared = { v: 1 };
stringify([shared, shared]);   // '[{"v":1},{"v":1}]'
JAVASCRIPT
stringify({ a: 1, b: { c: 2 } }, null, 2);
// '{\n  "a": 1,\n  "b": {\n    "c": 2\n  }\n}'

stringify({ a: 1, b: 2, c: 3 }, ["c", "a"]);   // '{"c":3,"a":1}'

Environment

  • Plain JavaScript in a browser page; the tests call the global stringify from stringify.js, and compare each result with the real JSON.stringify.
  • JSON.stringify is not allowed: while your function runs, the tests replace it with a function that throws. JSON.parse is out of scope too. Other built-ins (Object.keys, Array.isArray, String, toString(16)) are fine.
  • Proxies, document.all, objects that only inherit from Number.prototype, String.prototype or Boolean.prototype without wrapping a value, and the exact text of the error messages are not tested.

Hints

  1. The real algorithm serializes one property at a time: given a holder object and a key, what does it write? How does the top-level value fit that shape?
  2. What must the function remember while it is inside an object, so that it can tell a cycle from a shared object?
  3. Where do the indent of the current level and the indent of the level around it come from, when the closing bracket is written?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…