PHP: How to encode infinity or NaN numbers to JSON?

You are right about the JSON spec:

Numeric values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted.

The solution must also come from the spec, since a custom “JSON” encoder would not produce valid JSON anyway (you would have to write a custom decoder as well, and then you and consumers of your data would be forced to use that until the end of time).

Here’ what the spec allows for values:

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

false null true

So, any workaround that involves legal JSON instead of a custom JSON-like protocol would involve using something else instead of numbers.

One reasonable option would be to use the strings "Infinity" and "NaN" for these edge cases.

Leave a Comment