I am trying to add BigInt
support within my library, and ran into an issue with JSON.stringify
.
The nature of the library permits not to worry about type ambiguity and de-serialization, as everything that's serialized goes into the server, and never needs any de-serialization.
I initially came up with the following simplified approach, just to counteract Node.js throwing TypeError: Do not know how to serialize a BigInt
at me:
// Does JSON.stringify, with support for BigInt:
function toJson(data) {
return JSON.stringify(data, (_, v) => typeof v === 'bigint' ? v.toString() : v);
}
But since it converts each BigInt
into a string, each value ends up wrapped into double quotes.
Is there any work-around, perhaps some trick within Node.js formatting utilities, to produce a result from JSON.stringify
where each BigInt
would be formatted as an open value? This is what PostgreSQL understands and supports, and so I'm looking for a way to generate JSON with BigInt
that's compliant with PostgreSQL.
Example
const obj = {
value: 123n
};
console.log(toJson(obj));
// This is what I'm getting: {"value":"123"}
// This is what I want: {"value":123}
Obviously, I cannot just convert BigInt
into number
, as I would be losing information then. And rewriting the entire JSON.stringify
for this probably would be too complicated.
UPDATE
At this point I have reviewed and played with several polyfills, like these ones:
But they all seem like an awkward solution, to bring in so much code, and then modify for BigInt
support. I am hoping to find something more elegant.