Skip to content

Instantly share code, notes, and snippets.

@lordscales91
Created January 1, 2026 12:31
Show Gist options
  • Select an option

  • Save lordscales91/d24dd4bf09299a8646daeca90b4943b3 to your computer and use it in GitHub Desktop.

Select an option

Save lordscales91/d24dd4bf09299a8646daeca90b4943b3 to your computer and use it in GitHub Desktop.
An ugly but effective way of serializing and parsing Javascript bigints.
/*
* This uggly patch around the built-in JSON.stringify and JSON.parse exists mainly to bridge the gap between JS number
* which can only safely represent integers up to 2^53 - 1 and systems that support larger boundaries.
*/
BigInt.prototype.toJSON = function() {
return `$bigint:${this.toString()}`;
}
function bigIntReviver(_k, value, context) {
const rawValue = context?.source;
if(typeof rawValue === 'string'
&& rawValue.match(/^\-?\d+$/g)) {
const maybeBig = BigInt(rawValue);
if(maybeBig < Number.MIN_SAFE_INTEGER
|| maybeBig > Number.MAX_SAFE_INTEGER) {
return maybeBig;
}
}
return value;
}
const origJsonStringify = JSON.stringify;
JSON.stringify = function(value, replacer, space) {
const formatted = origJsonStringify(value, replacer, space);
return formatted.replaceAll(/"\$bigint:(\-?\d+)"/g, '$1');
}
const origJsonParse = JSON.parse;
JSON.parse = function(value, reviver) {
if(typeof reviver === 'function') {
return origJsonParse(value, reviver);
}
return origJsonParse(value, bigIntReviver);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment