nbjson.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 COPYING, distributed as part of this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. from base64 import encodestring
  15. from .rwbase import NotebookReader, NotebookWriter
  16. from .nbbase import from_dict
  17. import json
  18. #-----------------------------------------------------------------------------
  19. # Code
  20. #-----------------------------------------------------------------------------
  21. class JSONReader(NotebookReader):
  22. def reads(self, s, **kwargs):
  23. nb = json.loads(s, **kwargs)
  24. return self.to_notebook(nb, **kwargs)
  25. def to_notebook(self, d, **kwargs):
  26. """Convert from a raw JSON dict to a nested NotebookNode structure."""
  27. return from_dict(d)
  28. class JSONWriter(NotebookWriter):
  29. def writes(self, nb, **kwargs):
  30. kwargs['indent'] = 4
  31. return json.dumps(nb, **kwargs)
  32. _reader = JSONReader()
  33. _writer = JSONWriter()
  34. reads = _reader.reads
  35. read = _reader.read
  36. to_notebook = _reader.to_notebook
  37. write = _writer.write
  38. writes = _writer.writes