22.1. Implement JSON.stringify
Topics
This question is in
22. SerializationEvery request body, every localStorage entry and every log line that holds an object goes through JSON.stringify. It looks simple, but it makes a lot of quiet decisions: a property set to undefined disappears from an object but turns into null in an array, a Date turns into a string, NaN turns into null, and an object that contains itself makes it throw. Rebuilding it is the best way to learn every one of those rules.
Write stringify(value, replacer, space) in stringify.js. It returns the same result as JSON.stringify(value, replacer, space) for every value: the same string, the same undefined, or a TypeError in the same cases.
Signature
function stringify(value, replacer, space) // returns a string or undefinedvalue: any value.replacer(optional): a function(key, value)that can change each value, or an array of the keys to keep in objects. Anything else is ignored.space(optional): a number of spaces, or a string, used to indent the output.
Requirements
null,true,false, strings and finite numbers are written as JSON.-0is written as0.NaN,Infinityand-Infinitybecomenull.undefined, functions and symbols have no JSON form: at the top level the result isundefined, in an object the property is left out, and in an array the item becomesnull.- Objects list their own enumerable string keys, in
Object.keysorder, with no spaces:{"a":1,"b":[1,2]}. Symbol keys, non-enumerable and inherited properties are skipped. Getters are read. - Arrays write every index from 0 to
length - 1, withlengthread once before the first item (an array that grows or shrinks while it is written still gives that many items); a hole becomesnull. Extra properties on an array are ignored. - Strings and keys are quoted.
"and\are escaped;\b \f \n \r \tuse their short forms; other characters below U+0020 become\u00XX(lower-case hex); a lone surrogate becomes\udXXX; everything else, including emoji, is kept as it is. Number,StringandBooleanobjects are written as the primitive they hold. ABooleanobject's ownvalueOfdoes not change that.- When a value (an object, including a function, or a bigint) has a
toJSONmethod, its result is written instead.toJSONis called with the value asthisand the property key as its argument (""at the top level,"0","1"… in arrays). Dates are written this way. - A bigint throws a
TypeError, unless atoJSONturns it into something else. - An object or array that contains itself, at any depth, throws a
TypeError. The same object appearing twice side by side is not a cycle and is written twice. - A replacer function is called for every value, after
toJSON, with the containing object asthis: first with key""on a wrapper object{ "": value }, then for every member. Its return value is written instead;undefinedleaves an object member out. - A replacer array lists the keys to write in every object, in its order. Its strings and numbers (and
StringorNumberobjects) are used, each once; other items are ignored. Arrays still write every index. spaceas a number gives that many spaces per level (rounded down, at most 10; below 1 means none). As a string, its first 10 characters are used.NumberandStringobjects are unwrapped first. With a non-empty indent, every member goes on its own line,:is followed by one space, and empty objects and arrays stay{}and[].
Examples
stringify({ a: undefined, b: () => 1, c: [undefined, NaN], d: new Date(0) });
// '{"c":[null,null],"d":"1970-01-01T00:00:00.000Z"}'stringify('line\nbreak "quoted"'); // '"line\\nbreak \\"quoted\\""'
stringify(undefined); // undefined
stringify(10n); // throws TypeErrorconst node = { name: "root" };
node.self = node;
stringify(node); // throws TypeError
const shared = { v: 1 };
stringify([shared, shared]); // '[{"v":1},{"v":1}]'stringify({ a: 1, b: { c: 2 } }, null, 2);
// '{\n "a": 1,\n "b": {\n "c": 2\n }\n}'
stringify({ a: 1, b: 2, c: 3 }, ["c", "a"]); // '{"c":3,"a":1}'Environment
- Plain JavaScript in a browser page; the tests call the global
stringifyfromstringify.js, and compare each result with the realJSON.stringify. JSON.stringifyis not allowed: while your function runs, the tests replace it with a function that throws.JSON.parseis out of scope too. Other built-ins (Object.keys,Array.isArray,String,toString(16)) are fine.- Proxies,
document.all, objects that only inherit fromNumber.prototype,String.prototypeorBoolean.prototypewithout wrapping a value, and the exact text of the error messages are not tested.
Hints
- The real algorithm serializes one property at a time: given a holder object and a key, what does it write? How does the top-level value fit that shape?
- What must the function remember while it is inside an object, so that it can tell a cycle from a shared object?
- Where do the indent of the current level and the indent of the level around it come from, when the closing bracket is written?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it