fork(1) download
  1. import json
  2.  
  3. class FloatEncoder(json.JSONEncoder):
  4.  
  5. def __init__(self, nan_str = "null", **kwargs):
  6. super(FloatEncoder,self).__init__(**kwargs)
  7. self.nan_str = nan_str
  8.  
  9. #uses code from official python json.encoder module. Same licence applies.
  10. def iterencode(self, o, _one_shot=False):
  11. """Encode the given object and yield each string
  12. representation as available.
  13.  
  14. For example::
  15.  
  16. for chunk in JSONEncoder().iterencode(bigobject):
  17. mysocket.write(chunk)
  18.  
  19. """
  20. if self.check_circular:
  21. markers = {}
  22. else:
  23. markers = None
  24. if self.ensure_ascii:
  25. _encoder = json.encoder.encode_basestring_ascii
  26. else:
  27. _encoder = json.encoder.encode_basestring
  28. if self.encoding != 'utf-8':
  29. def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
  30. if isinstance(o, str):
  31. o = o.decode(_encoding)
  32. return _orig_encoder(o)
  33.  
  34. def floatstr(o, allow_nan=self.allow_nan,
  35. _repr=json.encoder.FLOAT_REPR, _inf=json.encoder.INFINITY, _neginf=-json.encoder.INFINITY, nan_str = self.nan_str):
  36. # Check for specials. Note that this type of test is processor
  37. # and/or platform-specific, so do tests which don't depend on the
  38. # internals.
  39.  
  40. if o != o:
  41. text = nan_str
  42. elif o == _inf:
  43. text = 'Infinity'
  44. elif o == _neginf:
  45. text = '-Infinity'
  46. else:
  47. return _repr(o)
  48.  
  49. if not allow_nan:
  50. raise ValueError(
  51. "Out of range float values are not JSON compliant: " +
  52. repr(o))
  53.  
  54. return text
  55.  
  56. _iterencode = json.encoder._make_iterencode(
  57. markers, self.default, _encoder, self.indent, floatstr,
  58. self.key_separator, self.item_separator, self.sort_keys,
  59. self.skipkeys, _one_shot)
  60. return _iterencode(o, 0)
  61.  
  62.  
  63. example_obj = {'name': 'example', 'body': [1.1, {"3.3": 5, "1.1": float('Nan')}, [float('inf'), 2.2]]}
  64. print json.dumps(example_obj, cls=FloatEncoder)
Success #stdin #stdout 0.02s 8180KB
stdin
Standard input is empty
stdout
{"body": [1.1, {"3.3": 5, "1.1": null}, [Infinity, 2.2]], "name": "example"}