101

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?

smci
  • 32,567
  • 20
  • 113
  • 146
shreyas
  • 2,510
  • 4
  • 19
  • 20
  • What does the outputted JSON look like? NaN isn't a native data type in Python, so I'm surprised it works at all. – Daniel Roseman Jul 06 '11 at 19:31
  • 4
    @Daniel: Actually, if you do `float("nan")`, you can get it. And calling `json.dumps(float("nan"))` gives you "NaN". – Thomas K Jul 06 '11 at 19:52

3 Answers3

79

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.

Thomas K
  • 39,200
  • 7
  • 84
  • 86
44

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
Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
eiTan LaVi
  • 2,901
  • 24
  • 15
30

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.

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
Soren
  • 14,402
  • 4
  • 41
  • 67
  • You will have to fix that, look at the manual http://docs.python.org/library/json.html#basic-usage – Soren Jul 06 '11 at 20:08