我最近遇到了关于Nagios / Nagiosgraph生成的RRD文件json_encode(rrd_xport($options));
的问题。
json_encode()
返回rrd_xport()
作为元素值时, NaN
似乎会失败(因此返回FALSE)。例如(给定$ var = rrd_xport()的返回):
print_r($var)
输出:
Array
(
[1418265300] = 297
[1418265600] = 296.79333333333
[1418265900] = 296.8
[1418266200] = 295.79333333333
[1418266500] = 295.40666666667
[1418266800] = 296
[1418267100] = 296
[1418267400] = 296
[1418267700] = 295.6
[1418268000] = 296
[1418268300] = 296.00666666667
[1418268600] = 296.39333333333
[1418268900] = 295.59333333333
[1418269200] = 295.4
[1418269500] = 295.79333333333
)
json_encode($var)
输出:
{ “1418263800”:297, “1418264100”:297.40666666667, “1418264400”:297.39333333333, “1418264700”:297, “1418265000”:297, “1418265300”:297, “1418265600”:296.79333333333, “1418265900”: 296.8, “1418266200”:295.79333333333, “1418266500”:295.40666666667, “1418266800”:296, “1418267100”:296, “1418267400”:296, “1418267700”:295.6, “1418268000”:296, “1418268300”:296.00666666667, “1418268600”:296.39333333333, “1418268900”:295.59333333333, “1418269200”:295.4, “1418269500”:295.79333333333}
现在,当我们(rrd_xport)向元素值引入NaN
时,我们会看到json_encode()
spew:
新print_r($var)
输出:
Array
(
[1418265300] = 297
[1418265600] = 296.79333333333
[1418265900] = 296.8
[1418266200] = 295.79333333333
[1418266500] = 295.40666666667
[1418266800] = 296
[1418267100] = 296
[1418267400] = 296
[1418267700] = 295.6
[1418268000] = 296
[1418268300] = 296.00666666667
[1418268600] = 296.39333333333
[1418268900] = 295.59333333333
[1418269200] = 295.4
[1418269500] = 295.79333333333
[1418269800] = NAN
)
var_dump(json_encode($var))
输出:
布尔(假)
最后,我的问题是:处理这个问题最好的方法是什么?我们是否需要搜索整个数组并替换NaN
? (实际输出远远大于这个例子,而且是多维的)当然有更好的方法!
答案 0 :(得分:2)
JSON规范没有关于如何对NaN
或Inf
实体进行编码的内容:
Numeric values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted.
您应该迭代并将is_nan($v)
值替换为适用于JSON
的任何值,例如为null ...
或者您可以实现自己的js_encode
功能
答案 1 :(得分:1)
绕过数组循环,感谢vp_arth!
function killnan($maybeHasNan)
{
if (gettype($maybeHasNan) != "array")
{
echo "AHSHIT\n";
return;
}
$iMakedThis = Array();
foreach ($maybeHasNan as $key = $value)
{
if (gettype($value) == "array")
{
# go deeper neo
$iMakedThis[$key] = killnan($value);
}
elseif (gettype($value) == "double" && is_nan($value))
{
$iMakedThis[$key] = NULL;
}
else
{
$iMakedThis[$key] = $value;
}
}
return $iMakedThis;
}