Created
February 27, 2025 15:09
-
-
Save jonelf/8e5ccabfe8d2b376c7883cbab78272c5 to your computer and use it in GitHub Desktop.
JSON.stringify can't handle BigInt by using this replacer it can
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.