PHP:如何将无穷或NaN数字编码为JSON? [英] PHP: How to encode infinity or NaN numbers to JSON?

查看:530
本文介绍了PHP:如何将无穷或NaN数字编码为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,无穷大和NaN不是JSON规范的一部分,因此此PHP代码:

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

$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()函数的情况下正确编码这些数字?也许有一些解决方法?

Is there any way to correctly encode these numbers without writing my own json_encode() function? Maybe some workaround?

推荐答案

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

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

解决方法:

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

将IFN/NAN值预先转换为字符串值("Infinity"和"NaN"),并且当您要在JavaScript中使用这些值进行操作时,请使用以下构造:var number1 = (+numbers.positive_infinity);.这会将字符串值'Infinity'转换为数字Infinity表示形式.

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.

这篇关于PHP:如何将无穷或NaN数字编码为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆