PHP:如何将无穷大或NaN数编码为JSON?

Sep*_*ram 16 php json nan infinity

显然,infinity和NaN不是JSON规范的一部分,所以这个PHP代码:

$numbers = array();
$numbers ['positive_infinity'] = +INF;
$numbers ['negative_infinity'] = -INF;
$numbers ['not_a_number'] = NAN;
$array_print = print_r ($numbers, true);
$array_json = json_encode ($numbers);
echo "\nprint_r(): $array_print";
echo "\njson_encode(): $array_json";
Run Code Online (Sandbox Code Playgroud)

产生这个:

PHP Warning:  json_encode(): double INF does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
PHP Warning:  json_encode(): double -INF does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
PHP Warning:  json_encode(): double NAN does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8

print_r(): Array
(
    [positive_infinity] => INF
    [negative_infinity] => -INF
    [not_a_number] => NAN
)

json_encode(): {"positive_infinity":0,"negative_infinity":0,"not_a_number":0}
Run Code Online (Sandbox Code Playgroud)

有没有办法正确编码这些数字而不编写我自己的json_encode()函数?也许一些解决方法?

Jon*_*Jon 11

您对JSON规范是正确的:

不允许使用不能表示为数字序列(例如Infinity和NaN)的数字值.

解决方案也必须来自规范,因为自定义"JSON"编码器无论如何都不会生成有效的JSON(您也必须编写自定义解码器,然后您和数据的使用者将被迫使用它直到时间到).

这里'规范允许值:

JSON值必须是对象,数组,数字或字符串,或以下三个文字名称之一:

false null true
Run Code Online (Sandbox Code Playgroud)

因此,任何涉及合法JSON而不是类似自定义JSON协议的解决方法都将涉及使用其他内容而不是数字.

一个合理的选择是使用字符串"Infinity""NaN"这些边缘情况.


mde*_*ils 10

根据JSON规范,没有Infinity或NaN值:http://json.org/

解决方法:

  1. 拒绝使用JSON(纯JSON),并编写自己的json_encode函数,它将处理INF/NAN(分别转换为"Infinity"和"NaN"),并确保使用result = eval('(' + json + ')');客户端之类的东西解析JSON .

  2. 预先将您的IFN/NAN值转换为字符串值('Infinity'和'NaN'),当您要在JavaScript中使用这些值时,请使用以下结构:var number1 = (+numbers.positive_infinity);.这会将字符串值'Infinity'转换为数字Infinity表示.


小智 10

在我看来,这是JSON的一大缺点.不同的JSON编码器处理方式不同,可在此处找到快速概述:http://lavag.org/topic/16217-cr-json-labview/?p = 9958

一种解决方案是将+ inf编码为+ 1e9999,因为在大多数解码器中它将自然地溢出到+ inf,并且与-inf相同,为-1e9999.NaN要难得多.