json-schema-ref-parser icon indicating copy to clipboard operation
json-schema-ref-parser copied to clipboard

Custom JSON parser to handle bigint

Open SebastienGllmt opened this issue 7 months ago • 0 comments

Currently, this project relies on JSON.parse to load JSON files. However, JSON.parse is lossy on numbers larger than Number.MAX_SAFE_INTEGER

ex:

console.log(
    JSON.parse(`${Number.MAX_SAFE_INTEGER + 2}`)
);

Correct output: 9007199254740993 What JS actually prints: 9007199254740992

Some important things to note:

  1. You cannot solve this by just passing a custom resolver to JSON.parse. Unfortunately, you need to replace JSON.parse entirely to be able to resolve large numbers without precision loss
  2. There is no standard for how this case is handled. Should a library convert only numbers that exceed a certain value as bigint? That would cause the type of everything to become number | bigint everywhere which people may not want. In a lot of cases, the way to handle this ends up being context-specific

Given this, it may be best to just have an agreed-upon way to allow a user-provided JSON parser to use when resolving references

SebastienGllmt avatar Apr 11 '25 05:04 SebastienGllmt