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,\ffor 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-0gives"0");NaNand±Infinitygive"null". Booleans andnullas their names. - Arrays:
[a,b,c]with no spaces. An item that isundefined, a function or a symbol becomesnull(holes too). - Objects:
{"k":v}with no spaces, over own enumerable string keys in order. A property whose value isundefined, a function or a symbol is skipped. - If a value has a
toJSONmethod, call it and serialize the result (this is howDateworks). - At the top level,
undefined, a function or a symbol returnsundefined(not a string). - A
BigIntthrows aTypeError, 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 13. ⌘Enter runs, ⌘⇧Enter submits.