json_impl.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import logging
  2. import json as py_json
  3. from collections import OrderedDict
  4. from typing import Any
  5. try:
  6. import orjson
  7. any_to_json = orjson.dumps # pylint: disable=no-member
  8. except ImportError:
  9. orjson = None
  10. try:
  11. import ujson
  12. def _ujson_to_json(obj: Any) -> bytes:
  13. return ujson.dumps(obj).encode() # pylint: disable=c-extension-no-member
  14. except ImportError:
  15. ujson = None
  16. _ujson_to_json = None
  17. def _pyjson_to_json(obj: Any) -> bytes:
  18. return py_json.dumps(obj, separators=(',', ':')).encode()
  19. logger = logging.getLogger(__name__)
  20. _to_json = OrderedDict()
  21. _to_json['orjson'] = orjson.dumps if orjson else None # pylint: disable=no-member
  22. _to_json['ujson'] = _ujson_to_json if ujson else None
  23. _to_json['python'] = _pyjson_to_json
  24. any_to_json = _pyjson_to_json
  25. def set_json_library(impl: str = None):
  26. global any_to_json # pylint: disable=global-statement
  27. if impl:
  28. func = _to_json.get(impl)
  29. if func:
  30. any_to_json = func
  31. return
  32. raise NotImplementedError(f'JSON library {impl} is not supported')
  33. for library, func in _to_json.items():
  34. if func:
  35. logger.debug('Using %s library for writing JSON byte strings', library)
  36. any_to_json = func
  37. break
  38. set_json_library()