Skip to content

builtins.fromJSON with true lossless JSON number support #13996

@roberth

Description

@roberth

Is your feature request related to a problem?

The original JSON specification only specifies the syntax of numbers, and nothing about lossy representations of them. Converting JSON numbers to floats is lossy.

Furthermore, floats are undesirable due to their complexity and occasional implementation differences, especially in "corner cases" like NaN semantics.
Inheriting this complexity is not appropriate for a language with a focus on reproducibility, so we should make this complexity possible to avoid.

Proposed solution

As of writing, we only have a single fromJSON function without extra parameters.
Add a fromJSONWith params str primop where params.losslessNumbers = true; is the new default behavior.
When true it parses the JSON without converting numbers to floats. Instead, it converts them to a wrapper object of the shape { _type = "number"; number = "6.2"; }, where the attribute value of number corresponds to the unaltered JSON number string as parsed.

Have a corresponding toJSONWith that can unpack these number wrappers.

Alternative solutions

It's tempting to lowercase the E, and/or drop the +, as these do not normally affect the meaning of the number, but we can't be sure how an application treats these differences.

Additional context

Checklist


Add 👍 to issues you find important.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureFeature request or proposallanguageThe Nix expression language; parser, interpreter, primops, evaluation, etc

    Type

    No type

    Projects

    Status

    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions