Last active
March 8, 2019 14:40
-
-
Save nicolasparada/cb889f5ddfed3b22c5cebc7c19f6d62d to your computer and use it in GitHub Desktop.
JSON encoding with BigInt support
This file contains hidden or 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
/** | |
* @param {string} text | |
*/ | |
export function parseJSON(text) { | |
if (typeof text !== 'string') { | |
return null | |
} | |
text = text.replace(/([^\"]+\"\:\s*)(\d{16,})(\,\s*\"[^\"]+|}$)/g, '$1"$2"$3') | |
return JSON.parse(text, (_, v) => typeof v === 'string' && /^\d{16,}$/.test(v) ? BigInt(v) : v) | |
} | |
export function stringifyJSON(value) { | |
return JSON | |
.stringify(value, (_, v) => typeof v === 'bigint' ? v.toString() : v) | |
.replace(/([^\"]+\"\:\s*)(?:\")(\d{16,})(?:\")(\,\s*\"[^\"]+|}$)/g, '$1$2$3') | |
} | |
export default { | |
parse: parseJSON, | |
stringify: stringifyJSON, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment