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

2024-03-03

显然,无穷大和 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";

产生这个:

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_encode()功能?也许有一些解决方法?


你是对的JSON规范 http://www.ietf.org/rfc/rfc4627.txt:

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

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

以下是规范允许的值:

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

false null true

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

一种合理的选择是使用字符串"Infinity" and "NaN"对于这些边缘情况。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP:如何将无穷大或 NaN 数字编码为 JSON? 的相关文章

随机推荐