nbjson.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. import copy
  15. import json
  16. from .nbbase import from_dict
  17. from .rwbase import (
  18. NotebookReader, NotebookWriter, restore_bytes, rejoin_lines, split_lines
  19. )
  20. #-----------------------------------------------------------------------------
  21. # Code
  22. #-----------------------------------------------------------------------------
  23. class BytesEncoder(json.JSONEncoder):
  24. """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
  25. def default(self, obj):
  26. if isinstance(obj, bytes):
  27. return obj.decode('ascii')
  28. return json.JSONEncoder.default(self, obj)
  29. class JSONReader(NotebookReader):
  30. def reads(self, s, **kwargs):
  31. nb = json.loads(s, **kwargs)
  32. nb = self.to_notebook(nb, **kwargs)
  33. return nb
  34. def to_notebook(self, d, **kwargs):
  35. return restore_bytes(rejoin_lines(from_dict(d)))
  36. class JSONWriter(NotebookWriter):
  37. def writes(self, nb, **kwargs):
  38. kwargs['cls'] = BytesEncoder
  39. kwargs['indent'] = 1
  40. kwargs['sort_keys'] = True
  41. if kwargs.pop('split_lines', True):
  42. nb = split_lines(copy.deepcopy(nb))
  43. return json.dumps(nb, **kwargs)
  44. _reader = JSONReader()
  45. _writer = JSONWriter()
  46. reads = _reader.reads
  47. read = _reader.read
  48. to_notebook = _reader.to_notebook
  49. write = _writer.write
  50. writes = _writer.writes