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

后端 未结 5 554
情话喂你
情话喂你 2020-12-11 14:53

Apparently, infinity and NaN are not a part of JSON specification, so this PHP code:

$numbers = array();
$numbers [\'positive_infinity\'] = +INF;
$numbers [\         


        
5条回答
  •  再見小時候
    2020-12-11 15:23

    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.

提交回复
热议问题