nbjson.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """Read and write notebooks in JSON format."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import copy
  6. import json
  7. from .nbbase import from_dict
  8. from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, split_lines, strip_transient
  9. class BytesEncoder(json.JSONEncoder):
  10. """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
  11. def default(self, obj):
  12. """Get the default value of an object."""
  13. if isinstance(obj, bytes):
  14. return obj.decode("ascii")
  15. return json.JSONEncoder.default(self, obj)
  16. class JSONReader(NotebookReader):
  17. """A JSON notebook reader."""
  18. def reads(self, s, **kwargs):
  19. """Convert a string to a notebook."""
  20. nb = json.loads(s, **kwargs)
  21. nb = self.to_notebook(nb, **kwargs)
  22. nb = strip_transient(nb)
  23. return nb # noqa: RET504
  24. def to_notebook(self, d, **kwargs):
  25. """Convert a dict to a notebook."""
  26. return rejoin_lines(from_dict(d))
  27. class JSONWriter(NotebookWriter):
  28. """A JSON notebook writer."""
  29. def writes(self, nb, **kwargs):
  30. """Convert a notebook to a string."""
  31. kwargs["cls"] = BytesEncoder
  32. kwargs["indent"] = 1
  33. kwargs["sort_keys"] = True
  34. kwargs["separators"] = (",", ": ")
  35. nb = copy.deepcopy(nb)
  36. nb = strip_transient(nb)
  37. if kwargs.pop("split_lines", True):
  38. nb = split_lines(nb)
  39. return json.dumps(nb, **kwargs)
  40. _reader = JSONReader()
  41. _writer = JSONWriter()
  42. reads = _reader.reads
  43. read = _reader.read
  44. to_notebook = _reader.to_notebook
  45. write = _writer.write
  46. writes = _writer.writes