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

后端 未结 5 547
情话喂你
情话喂你 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:32

    According to JSON spec, there is no Infinity or NaN values: http://json.org/

    Workarounds:

    1. Reject using JSON (pure JSON), and write your own json_encode function, which will handle INF/NAN (converting to "Infinity" and "NaN" respectively), and make sure you are parsing JSON using something like result = eval('(' + json + ')'); on the client side.

    2. Pre convert your IFN/NAN values into string values ('Infinity' and 'NaN'), and when you are going to operate with those values in JavaScript, use the following construction: var number1 = (+numbers.positive_infinity);. This will convert string value 'Infinity' into numeric Infinity representation.

提交回复
热议问题