-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson-bigint.js
34 lines (32 loc) · 932 Bytes
/
json-bigint.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {string} text
* @param {function(any,any):any=} reviver
*/
export function parseJSON(text, reviver) {
if (typeof text !== 'string') {
return null
}
return JSON.parse(text.replace(/([^\"]+\"\:\s*)(\d{16,})(\,\s*\"[^\"]+|}$)/g, '$1"$2n"$3'), (k, v) => {
if (typeof v === 'string' && /^\d{16,}n$/.test(v)) {
v = BigInt(v.slice(0, -1))
}
return typeof reviver === 'function' ? reviver(k, v) : v
})
}
/**
* @param {*} value
* @param {(function(any,any):any)|((number|string)[])=} replacer
* @param {string|number=} space
*/
export function stringifyJSON(value, replacer, space) {
return JSON.stringify(value, (k, v) => {
if (typeof v === 'bigint') {
v = v.toString() + 'n'
}
return typeof replacer === 'function' ? replacer(k, v) : v
}, space).replace(/([^\"]+\"\:\s*)(?:\")(\d{16,})(?:n\")(\,\s*\"[^\"]+|}$)/g, '$1$2$3')
}
export default {
parse: parseJSON,
stringify: stringifyJSON,
}