PHP:如何将无穷大或NaN数字编码为JSON?
显然,infinity和NaN不是JSON规范的一部分,因此以下PHP代码:PHP:如何将无穷大或NaN数字编码为JSON?,php,json,nan,infinity,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); e
$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";
产生以下结果:
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}
有没有任何方法可以在不编写自己的json\u encode()
函数的情况下正确编码这些数字?也许有一些解决办法?您在以下方面是对的:
不允许使用不能表示为数字序列的数值(如无穷大和NaN)
解决方案还必须来自规范,因为自定义“JSON”编码器无论如何都不会生成有效的JSON(您还必须编写自定义解码器,然后您和数据消费者将被迫使用该解码器,直到时间结束)
以下是“规范允许的值:
JSON值必须是对象、数组、数字或字符串,或以下三个文字名称之一:
false null true
因此,任何涉及合法JSON而不是自定义JSON协议的解决方案都需要使用其他东西而不是数字
一个合理的选择是对这些边缘情况使用字符串
“Infinity”
和“NaN”
。根据JSON规范,没有无限或NaN值:
解决办法:
result=eval(“(“+JSON+”)”)的东西解析JSON代码>在客户端
var number1=(+numbers.positive_Infinity)代码>。这将把字符串值“Infinity”转换为数值Infinity
表示形式
在我看来,这是JSON的一大缺点。不同的JSON编码器以不同的方式处理此问题,可以在此处找到快速概述:
一种解决方案是将+inf编码为+1e9999,因为在大多数解码器中,这将自然溢出为+inf,而-inf编码为-1e9999。南更难 上面提到的警告,php文档中报告了官方错误
对于PHP>=5.5.0的较新版本,作为此问题读者的更新,要从
json_encode
获取INF
或NAN
值,将其编码为0
,而不是json_encode
无法输出,请添加该选项
例如:
json_encode($data,json_NUMERIC_CHECK | json_PARTIAL_OUTPUT_ON_ERROR)代码>+1用于引用规范和提及文字。但是,接受另一个答案,因为它提出了将它们转换回数字的方法。您还可以使用JSON.stringify(JSON,replace)
,其中replace
是将无限
,NaN
等替换为字符串表示形式的函数(请参见示例)