把 NaN 送进 json

我正在尝试使用 json.dumps()将一个包含 float 和 NaN的数组编码为 Python 中的 JSON 字符串。

但是编码的 JSON 字符串没有在 PHP 中成功解码。是 NaN引起了这个问题吗?我该怎么处理这种情况?

70396 次浏览

NaN is not a valid JSON symbol, see the spec at http://json.org/

Your encoder should probably have encoded the NaN as null instead.

json.dumps has an allow_nan parameter, which defaults to True.

NaN, Infinity and -Infinity are not part of JSON, but they are standard in Javascript, so they're commonly used extensions. If the recipient can't handle them, set allow_nan=False. But then you'll get ValueError when you try to serialise NaN.

The simplejson package on which Python's standard json package is based moves more quickly, and handles this situation. NaN is not valid JSON, and the ignore_nan flag will handle correctly all NaN to null conversions.

import simplejson as json
json.dumps(thing, ignore_nan=True)

The default parameter will allow simplejson to parse your datetimes correctly.

json.dumps(response, ignore_nan=True, default=datetime.datetime.isoformat)

simplejson can be installed with pip.

pip install simplejson