Skip to content

Instantly share code, notes, and snippets.

@nicolasparada
Last active March 8, 2019 14:40
Show Gist options
  • Save nicolasparada/cb889f5ddfed3b22c5cebc7c19f6d62d to your computer and use it in GitHub Desktop.
Save nicolasparada/cb889f5ddfed3b22c5cebc7c19f6d62d to your computer and use it in GitHub Desktop.
JSON encoding with BigInt support
/**
* @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