nbjson.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Read and write notebooks in JSON format.
  2. Authors:
  3. * Brian Granger
  4. """
  5. # -----------------------------------------------------------------------------
  6. # Copyright (C) 2008-2011 The IPython Development Team
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file LICENSE, distributed as part of this software.
  10. # -----------------------------------------------------------------------------
  11. # -----------------------------------------------------------------------------
  12. # Imports
  13. # -----------------------------------------------------------------------------
  14. from __future__ import annotations
  15. import copy
  16. import json
  17. from .nbbase import from_dict
  18. from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, restore_bytes, split_lines
  19. # -----------------------------------------------------------------------------
  20. # Code
  21. # -----------------------------------------------------------------------------
  22. class BytesEncoder(json.JSONEncoder):
  23. """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
  24. def default(self, obj):
  25. """The default value of an object."""
  26. if isinstance(obj, bytes):
  27. return obj.decode("ascii")
  28. return json.JSONEncoder.default(self, obj)
  29. class JSONReader(NotebookReader):
  30. """A JSON notebook reader."""
  31. def reads(self, s, **kwargs):
  32. """Convert a string to a notebook."""
  33. nb = json.loads(s, **kwargs)
  34. nb = self.to_notebook(nb, **kwargs)
  35. return nb # noqa: RET504
  36. def to_notebook(self, d, **kwargs):
  37. """Convert a string to a notebook."""
  38. return restore_bytes(rejoin_lines(from_dict(d)))
  39. class JSONWriter(NotebookWriter):
  40. """A JSON notebook writer."""
  41. def writes(self, nb, **kwargs):
  42. """Convert a notebook object to a string."""
  43. kwargs["cls"] = BytesEncoder
  44. kwargs["indent"] = 1
  45. kwargs["sort_keys"] = True
  46. if kwargs.pop("split_lines", True):
  47. nb = split_lines(copy.deepcopy(nb))
  48. return json.dumps(nb, **kwargs)
  49. _reader = JSONReader()
  50. _writer = JSONWriter()
  51. reads = _reader.reads
  52. read = _reader.read
  53. to_notebook = _reader.to_notebook
  54. write = _writer.write
  55. writes = _writer.writes