json.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. """
  2. Wrapper for the builtin json module that ensures compliance with the JSON spec.
  3. REST framework should always import this wrapper module in order to maintain
  4. spec-compliant encoding/decoding. Support for non-standard features should be
  5. handled by users at the renderer and parser layer.
  6. """
  7. import functools
  8. import json # noqa
  9. def strict_constant(o):
  10. raise ValueError('Out of range float values are not JSON compliant: ' + repr(o))
  11. @functools.wraps(json.dump)
  12. def dump(*args, **kwargs):
  13. kwargs.setdefault('allow_nan', False)
  14. return json.dump(*args, **kwargs)
  15. @functools.wraps(json.dumps)
  16. def dumps(*args, **kwargs):
  17. kwargs.setdefault('allow_nan', False)
  18. return json.dumps(*args, **kwargs)
  19. @functools.wraps(json.load)
  20. def load(*args, **kwargs):
  21. kwargs.setdefault('parse_constant', strict_constant)
  22. return json.load(*args, **kwargs)
  23. @functools.wraps(json.loads)
  24. def loads(*args, **kwargs):
  25. kwargs.setdefault('parse_constant', strict_constant)
  26. return json.loads(*args, **kwargs)