JSON.stringify() works well for plain JSON data, but it loses information for values like undefined, Date, and RegExp.
Popular libraries like SuperJSON and devalue were built to solve exactly this kind of problem.
Implement two functions:
serialize(value): returns a string.deserialize(serialized): returns the original value represented by that string.The exact serialized format is up to you. A common approach is to recursively convert the input into a JSON-safe tree with small tagged objects, then call JSON.stringify().
For this question, support:
undefinedNaN, Infinity, -InfinityBigIntDateRegExpSupported values can appear anywhere inside dense arrays and plain objects.
const value = {createdAt: new Date('2026-01-01T00:00:00.000Z'),retries: Infinity,missing: undefined,matcher: /user-\d+/gi,};const serialized = serialize(value);// Any string format is fine as long as deserialize(serialized)// recreates an equivalent value.const restored = deserialize(serialized);restored.createdAt instanceof Date; // truerestored.retries; // Infinityrestored.missing; // undefinedrestored.matcher.test('USER-42'); // true
const value = [undefined, BigInt(42), { score: NaN }];const restored = deserialize(serialize(value));restored[0]; // undefinedrestored[1]; // 42nNumber.isNaN(restored[2].score); // true
deserialize only receives strings produced by serialize.Map, Set, cyclic references, sparse arrays, malformed serialized strings, and custom class instances are out of scope.console.log() 语句将显示在此处。