freecrayon/JSONBigInt

Forks

Forked 1 time

JSON.parse and JSON.stringify that preserves BigInt values.

Works by encoding BigInt values into strings with a special prefix.

See https://www.val.town/v/freecrayon/JSONBigInt_example for an example of how to use it.

Readme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const prefix = "BIGINT::";
const prefixLength = prefix.length;
const stringify = (data: unknown, _?: null, padding?: number): string => {
return JSON.stringify(
data,
(_key, value) => (typeof value === "bigint" ? `${prefix}${value}` : value),
padding,
);
};
const parse = (data: string): unknown => {
return JSON.parse(data, (_key, value) => {
if (typeof value === "string" && value.startsWith(prefix)) {
return BigInt(value.slice(prefixLength));
}
return value;
});
};
export { parse, stringify };
1
Next