Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created February 27, 2025 15:09
Show Gist options
  • Save jonelf/8e5ccabfe8d2b376c7883cbab78272c5 to your computer and use it in GitHub Desktop.
Save jonelf/8e5ccabfe8d2b376c7883cbab78272c5 to your computer and use it in GitHub Desktop.
JSON.stringify can't handle BigInt by using this replacer it can
// Stringify using the replacer
// const jsonBigInteger = JSON.stringify(bigInteger, bigIntReplacer);
// Parse from JSON
// const fromJsonBigInteger = JSON.parse(jsonBigInteger, bigIntReviver);
export function bigIntReplacer(key: string, value: any): any {
if (typeof value === "bigint") {
return value.toString() + "n";
}
return value;
}
export function bigIntReviver(key: string, value: any): any {
if (typeof value === "string" && /^\d+n$/.test(value)) {
return BigInt(value.slice(0, -1));
}
return value;
}
@jonelf
Copy link
Author

jonelf commented Feb 28, 2025

Be aware of a problem with this solution. If you have the string "107n" that's actually a string and not a BigInt then that will be revived as a BigInt. I propose only using the replacer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment