Skip to content

Custom JSON parser to handle bigint #379

Open
@SebastienGllmt

Description

@SebastienGllmt

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions