Reimplement JSON.stringify with indentation from scratch
A log viewer lets engineers expand any event and read its payload as nicely indented JSON. The viewer runs in an embedded runtime that has no JSON global, so you have to write the serializer yourself, and it must produce exactly what the browser would.
Implement prettyJSON(value, indent). It returns the same result as JSON.stringify(value, null, indent).
prettyJSON(value, indent?) // => string | undefined
null and booleans become null, true, false.String(number) (so -0 becomes 0). NaN, Infinity and -Infinity become null." as \" and \ as \\; the control characters backspace, form feed, newline, carriage return and tab as \b, \f, \n, \r, \t; every other character below U+0020 as \u00XX with lowercase hex (for example \u0007). All other characters are copied as they are. Object keys are escaped the same way.0 to length - 1. Holes, undefined, functions and symbols become null.Object.keys order. Properties whose value is undefined, a function or a symbol are left out. This means a Map, a Set or a class instance only shows its own enumerable fields (often {}).toJSON method, call it as value.toJSON(key) and serialize its return value instead. key is the property name, the array index as a string ('0', '1', …), or '' for the root value. This is how a Date turns into its ISO string.undefined, a function or a symbol returns undefined (not a string).BigInt anywhere throws a TypeError.TypeError. The same object appearing twice in different branches is fine.Tests do not use boxed primitives (new String('x')) or lone surrogate characters.
indent is a number, each level is indented by that many spaces, at most 10. A number below 1 means no indentation.indent is a string, its first 10 characters are used as the indentation for each level. An empty string means no indentation.indent (including leaving it out) means no indentation.{"a":[1,2]}."key": value, with one space after the colon.[] and {}, also when every property was left out.prettyJSON({ id: 7, tags: ['a'], meta: {}, skip: undefined });
// => '{"id":7,"tags":["a"],"meta":{}}'
prettyJSON({ id: 7, tags: ['a', null], meta: {} }, 2);
// =>
// {
// "id": 7,
// "tags": [
// "a",
// null
// ],
// "meta": {}
// }
prettyJSON([NaN, () => 1, 'say "hi"\n']); // => '[null,null,"say \\"hi\\"\\n"]'
prettyJSON(new Date(Date.UTC(2026, 0, 2))); // => '"2026-01-02T00:00:00.000Z"'
prettyJSON(undefined); // => undefined
prettyJSON([1], '--'); // => '[\n--1\n]'
const loop = {};
loop.self = loop;
prettyJSON(loop); // throws TypeError
prettyJSON(10n); // throws TypeError
JSON.stringify.