Is it possible to parse a JSON string like '{id: 3458764513820541000}' using zod without resorting to an additional library like json-bigint?
2 Answers
You can use the second argument of JSON.parse -- a reviver function -- and have that function return a BigInt whenever the source being parsed represents an integer that is not in the safe integer range for the number type:
const data = JSON.parse('{"id": 3458764513820541000, "val": 42}', reviver);
console.log(typeof data.id, typeof data.val);
function reviver(key, value, {source}) {
if (Number.isInteger(+source) && !Number.isSafeInteger(+source)) {
return BigInt(source);
}
return value;
}
1 Comment
Emre
It seems this
{source} is only present in newer runtimes. caniuse.com/…Zod alone cannot safely parse large integers in JSON, because JSON.parse loses precision above 2^53 - 1. For safetly try to use json-bigint to parse the JSON, then validate with Zod
import JSONbig from 'json-bigint';
import { z } from 'zod';
const data = JSONbig.parse('{"id": 3458764513820541000}');
const schema = z.object({ id: z.bigint() });
schema.parse(data);