by EdSchouten · 2y ago · 0 comments
https://pkg.go.dev/encoding/json#Decoder.UseNumber
That allows you to capture/forward numbers without any loss of precision.
To wit, Python's json module has `parse_float` and `parse_int` hooks:
https://docs.python.org/3/library/json.html#encoders-and-dec...
Example:
>>> json.loads('{"int":12345,"float":123.45}', parse_int=str, parse_float=str)
{'int': '12345', 'float': '123.45'}
FWIW, when I've cared about interop and controlled the schema, I've specified JSON strings for numbers, along with the range, precision, and representation. This is no worse (nor better) than using RFC 3339 for dates.This example on MDN seems to indicate that you can, am I misunderstanding it?
const bigJSON = '{"gross_gdp": 12345678901234567890}';
const bigObj = JSON.parse(bigJSON, (key, value, context) => {
if (key === "gross_gdp") {
// Ignore the value because it has already lost precision
return BigInt(context.source);
}
return value;
});
[0]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...With Zod, you can use z.bigint() parser. If you take the "parse any JSON" snippet https://zod.dev/?id=json-type and change z.number() to z.bigint(), it should do what you are looking for.