jsonapi.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """JSON serialize to/from utf8 bytes
  2. .. versionchanged:: 22.2
  3. Remove optional imports of different JSON implementations.
  4. Now that we require recent Python, unconditionally use the standard library.
  5. Custom JSON libraries can be used via custom serialization functions.
  6. """
  7. # Copyright (C) PyZMQ Developers
  8. # Distributed under the terms of the Modified BSD License.
  9. from __future__ import annotations
  10. import json
  11. from typing import Any
  12. # backward-compatibility, unused
  13. jsonmod = json
  14. def dumps(o: Any, **kwargs) -> bytes:
  15. """Serialize object to JSON bytes (utf-8).
  16. Keyword arguments are passed along to :py:func:`json.dumps`.
  17. """
  18. return json.dumps(o, **kwargs).encode("utf8")
  19. def loads(s: bytes | str, **kwargs) -> dict | list | str | int | float:
  20. """Load object from JSON bytes (utf-8).
  21. Keyword arguments are passed along to :py:func:`json.loads`.
  22. """
  23. if isinstance(s, bytes):
  24. s = s.decode("utf8")
  25. return json.loads(s, **kwargs)
  26. __all__ = ['dumps', 'loads']