CodePark/ problems / JSON.stringify
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Parsing and building strings

JSON.stringify

hardabout 35 minutes in an interview

Implement jsonStringify(value), which matches JSON.stringify(value) (no replacer or space arguments) for the cases below. Don't call JSON.stringify.

Primitives:

  • null, true and false are written as null, true and false.
  • Finite numbers are written as String(n), so -0 becomes 0 and 1e21 becomes 1e+21. NaN, Infinity and -Infinity become null.
  • Strings are wrapped in double quotes. Escape " as \" and \ as \\. Escape the control characters backspace, form feed, newline, carriage return and tab as \b, \f, \n, \r and \t. Any other character below code 32 becomes \u plus 4 lowercase hex digits, for example \u0001. Everything else is written as it is.
  • A bigint throws a TypeError.

Containers are written with no spaces:

  • Arrays: [item,item].
  • Objects: {"key":value,...} for each own key from Object.keys, in that order. Keys are quoted and escaped like strings.
  • If a value has a toJSON method (dates do), write what toJSON() returns instead.

Values JSON can't hold (undefined, functions, symbols): at the top level, return undefined. As an object property, leave the property out. As an array item, write null.

Cycles: if an object contains itself, directly or deeper down, throw a TypeError. The same object appearing twice without a cycle is fine.

Input: jsonStringify({ id: 7, tags: ['a'], at: undefined }) Output: '{"id":7,"tags":["a"]}'
Input: jsonStringify([NaN, () => 1, 'say "hi"']) Output: '[null,null,"say \\"hi\\""]'
Input: jsonStringify(undefined) Output: undefined