nbjson.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 json
  16. from .nbbase import from_dict
  17. from .rwbase import NotebookReader, NotebookWriter
  18. # -----------------------------------------------------------------------------
  19. # Code
  20. # -----------------------------------------------------------------------------
  21. class JSONReader(NotebookReader):
  22. """A JSON notebook reader."""
  23. def reads(self, s, **kwargs):
  24. """Convert a string to a notebook object."""
  25. nb = json.loads(s, **kwargs)
  26. return self.to_notebook(nb, **kwargs)
  27. def to_notebook(self, d, **kwargs):
  28. """Convert from a raw JSON dict to a nested NotebookNode structure."""
  29. return from_dict(d)
  30. class JSONWriter(NotebookWriter):
  31. """A JSON notebook writer."""
  32. def writes(self, nb, **kwargs):
  33. """Convert a notebook object to a string."""
  34. kwargs["indent"] = 4
  35. return json.dumps(nb, **kwargs)
  36. _reader = JSONReader()
  37. _writer = JSONWriter()
  38. reads = _reader.reads
  39. read = _reader.read
  40. to_notebook = _reader.to_notebook
  41. write = _writer.write
  42. writes = _writer.writes