Harmonizing the JSON serialization of non-finite float values with browsers and other languages

Previous discussion

This is an adapted version of a GitHub issue. Mark Dickinson suggested I create a thread here since GitHub is not the primary place of discussion.
For links to previous discussions and a corresponding PR, please refer to this issue. I can’t attach more than two links since I’m a new user.


Currently, python’s default JSON serializer encodes values like NaN as-is, with the explanation being that many JS-based JSON libraries also do this, and that the corresponding parsers can handle such non-conforming input.
In reality, most major browsers do not support this type of encoding and even NodeJS(v14.16.0) converts such values to null.
The keyword argument allow_nan makes the serializer throw when encountering non-finite values when set to True, but I’d argue it is paramount to ensure compatibility with modern browsers, instead of just stopping execution. Changing the default behavior is of course not needed or possible at this point.

When implementing this feature, there are two main decisions to make.

Firstly, it has to be decided if allow_nan should be extended to take more datatypes like strings and callables, or if we should create a separate argument for this functionality.
Re-purposing allow_nan would make the control over such behavior centralized, however the name is very limiting.
It doesn’t say anything about other non-finite values, and without looking at the docs, one would think it only takes bool values.

Secondly, it has to be decided how far we want to take this feature.
Do we want to have pre-defined cases like as_is, throw, and to_null, or do we want to allow the user to pass their own callable? The latter is implemented by the linked PR. Having both options is also a possibility.
There has also been a discuss thread that suggested adding a general override for all built-in types, though it seems like the sentiment is against making the standard JSON serializer more complex than it already is.

Overall, each combination of decisions has its advantages and drawbacks. Since I wasn’t a part of such discussions before, I don’t have a preference.
All I want is to see this feature get implemented, and I can create a PR once consensus is reached.