1

Is it possible to parse a JSON string like '{id: 3458764513820541000}' using zod without resorting to an additional library like json-bigint?

2 Answers 2

2

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;
}

Sign up to request clarification or add additional context in comments.

1 Comment

It seems this {source} is only present in newer runtimes. caniuse.com/…
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.