Readme

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.

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 };
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v1
March 30, 2024