sending NaN in json

shreyas picture shreyas · Jul 6, 2011 · Viewed 35.3k times · Source

I am trying to encode an array which contains floats and NaN into JSON string from Python using json.dumps().

But the encoded JSON string is not being decoded successfully in PHP. Is the NaN causing this problem? How can I work around this situation?

Answer

Thomas K picture Thomas K · Jul 6, 2011

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.