Skip to content
Onsite

JSON.stringify Implementation

HardP2Coding

Implement stringify(value), a version of JSON.stringify with no replacer and no indentation. Do not call JSON.stringify.

Output must match the real function for these rules:

  • Strings are wrapped in double quotes; escape the double quote and the backslash, use \n, \r, \t, \b, \f for those control characters, and \u00XX (lower-case hex, four digits) for any other character below U+0020. All other characters are written as they are.
  • Numbers: finite numbers as String(n) (so -0 gives "0"); NaN and ±Infinity give "null". Booleans and null as their names.
  • Arrays: [a,b,c] with no spaces. An item that is undefined, a function or a symbol becomes null (holes too).
  • Objects: {"k":v} with no spaces, over own enumerable string keys in order. A property whose value is undefined, a function or a symbol is skipped.
  • If a value has a toJSON method, call it and serialize the result (this is how Date works).
  • At the top level, undefined, a function or a symbol returns undefined (not a string).
  • A BigInt throws a TypeError, and so does a circular reference.

Example 1

Input
stringify({ a: [1, 'x', undefined], b: undefined, c: new Date(0) })
Output
'{"a":[1,"x",null],"c":"1970-01-01T00:00:00.000Z"}'

Constraints

  • Nesting depth <= 1000
  • Total size <= 10^5 values

Hints

Run checks the 3 visible tests, Submit all 13.