Stringify and parse NaN, BigInt, Date, Map without data loss
JSON.stringify silently loses data. It turns NaN into null, drops undefined properties, throws on BigInt, turns dates into strings, and turns a Map into {}. When an app sends state between a server and a client, or saves it to storage, those losses become bugs.
Build richJSON, an object with two methods:
richJSON.stringify(value) // => string (valid JSON)
richJSON.parse(text) // => the original value
For every supported value, richJSON.parse(richJSON.stringify(value)) must give back a value deeply equal to the original, with the same types.
null, booleans, and strings.NaN, Infinity, -Infinity, and -0 (which must come back as -0, not 0).undefined: at the root, as an array element, and as an object property value. A property whose value is undefined must still exist after the round trip ('key' in result is true).BigInt, of any size and sign.Date, including invalid dates (new Date('nope')), which must come back as an invalid Date.RegExp, keeping its source and flags.Map and Set, keeping insertion order. Map keys can be any supported value, not just strings.stringify returns a string that JSON.parse accepts.'undefined', '$NaN', or { __type: 'Date', value: '2024-01-01' }).const snapshot = {
savedAt: new Date('2026-03-14T09:26:53.000Z'),
views: 9007199254740993n,
ratio: NaN,
cursor: undefined,
tags: new Set(['draft', 'shared']),
owners: new Map([[42, { name: 'Lena' }]]),
match: /^ord_\d+$/gi,
};
const text = richJSON.stringify(snapshot);
typeof text; // => 'string'
JSON.parse(text); // does not throw
const copy = richJSON.parse(text);
copy.savedAt instanceof Date; // => true
copy.views === 9007199254740993n; // => true
Number.isNaN(copy.ratio); // => true
'cursor' in copy; // => true
copy.tags.has('shared'); // => true
copy.owners.get(42).name; // => 'Lena'
copy.match.flags; // => 'gi'
Object.is(richJSON.parse(richJSON.stringify(-0)), -0); // => true
richJSON.parse(richJSON.stringify({ __type: 'Date', value: 'x' }));
// => { __type: 'Date', value: 'x' } (still a plain object)