nbjson.py 1.5 KB

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