-
-
Notifications
You must be signed in to change notification settings - Fork 142
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
What is the expected behavior of serializing BigInt to JSON? #515
Comments
The above representation is a spec violation according to IETF RFC8259: The JavaScript Object Notation (JSON) Data Interchange Format. I think you should handle it similar to how Serialization into strings// POJO
{
// Serialize into integer with n at the end
commentId: 9_007_199_254_740_999n,
// Serialize into ISO8601 format
createdAt: new Date("2023-10-05T12:34:56"),
// Serialize into regular expression that can be passed back in to RegExp constructor
regEx: /abc[dD]/
}
// JSON
{
"commentId": "9007199254740999n",
"createdAt": "2023-10-05T12:34:56",
"regEx": "abc[dD]"
} Pros:
Cons:
Serialization into plain number// POJO
{
// Serialize into an integer
commentId: 9_007_199_254_740_999n,
// Serialize into UNIX epoch in seconds
createdAt: new Date("2023-10-05T12:34:56")
}
// JSON
{
"commentId": 9007199254740999,
"createdAt": 1696509296,
} Pros:
Cons:
|
Thank you. What do you think about just throwing an error if an attempt it made to serialize BigInt into JSON?, i.e. require that user cast the value to X before serialization, e.g. await pool.oneFirst(sql.unsafe`
SELECT json_object_agg('foo', ${BigInt(9_007_199_254_740_999n)}::bigint::text)
`); The above is perfectly fine. My thinking is that this way the handling of the value does not depend on Slonik and it is less likely to produce unexpected results. The error message could include suggestions of how to cast the value. |
I think throwing an error may be a valid behavior because Just to highlight how error-prone handling In PostgreSQL However, Reading 64-bit integer out of PostgreSQL as Therefore, the most analogous data type in PostgreSQL is not actually Basic rule of thumb should be:
|
In raw psql client, PostgreSQL seems to take Option 2 and serialize into plain number for JSON: SELECT json_build_object('biggerThan64bit', '9223372036854775809'::numeric) AS big_json;
-- Returns {"biggerThan64bit": 9223372036854775809} So at least PL/pgSQL dialect seems to treat that as a valid JSON fwiw, regardless of whether this causes issues for node-postgres driver. Executing in TablePlus: |
Very interesting. Learned a lot! Thank you |
You're welcome! PS: Also forgot to mention
|
given this test:
What is the expected value of the result?
I would think it should be
{foo: BigInt(9_007_199_254_740_999n)}
, but I am not certain if that is even possible, nor would that be valid JSON.I am leaning towards throwing an error.
Probably related to #513
The text was updated successfully, but these errors were encountered: