Write Your Own JSON.stringify

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write stringify(value, indent), your own JSON.stringify for plain data, without calling the real one. null, true and false are written as they are, and a finite number as String(number) writes it; NaN, Infinity and -Infinity become null. Strings, and object keys, go in double quotes, with a backslash before each double quote and backslash. Backspace, form feed, newline, carriage return and tab become a backslash followed by b, f, n, r or t, and any other character with a code below 32 becomes a backslash, a u and the code as four lowercase hex digits. Arrays and objects are written with everything inside them; objects use their own enumerable keys, in Object.keys order. In an object, a property whose value is undefined, a function or a symbol is left out; in an array, such an item becomes null; on its own, it gives undefined. A value with a toJSON method, such as a Date, is written as what toJSON returns. indent is a number of spaces from 0 to 10, default 0: above 0, each item and property goes on its own line, indented one level more than the line that opens its array or object, with a space after each colon, and empty arrays and objects stay [] and {}. A value that contains itself throws a TypeError, but the same object appearing twice, side by side, is fine.

Your code must pass

  • Writes primitives and escapes strings
  • Writes nested arrays and objects
  • Turns NaN, Infinity and missing values into null or leaves them out
  • Uses toJSON, like Dates do
  • Indents with the given number of spaces
  • Throws a TypeError for cycles but not for shared objects