nbjson.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. from __future__ import annotations
  5. import copy
  6. import json
  7. from nbformat.notebooknode import from_dict
  8. from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, split_lines, strip_transient
  9. class BytesEncoder(json.JSONEncoder):
  10. """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
  11. def default(self, obj):
  12. """Get the default value of an object."""
  13. if isinstance(obj, bytes):
  14. return obj.decode("ascii")
  15. return json.JSONEncoder.default(self, obj)
  16. class JSONReader(NotebookReader):
  17. """A JSON notebook reader."""
  18. def reads(self, s, **kwargs):
  19. """Read a JSON string into a Notebook object"""
  20. nb = json.loads(s, **kwargs)
  21. nb = self.to_notebook(nb, **kwargs)
  22. return nb # noqa: RET504
  23. def to_notebook(self, d, **kwargs):
  24. """Convert a disk-format notebook dict to in-memory NotebookNode
  25. handles multi-line values as strings, scrubbing of transient values, etc.
  26. """
  27. nb = from_dict(d)
  28. nb = rejoin_lines(nb)
  29. nb = strip_transient(nb)
  30. return nb # noqa: RET504
  31. class JSONWriter(NotebookWriter):
  32. """A JSON notebook writer."""
  33. def writes(self, nb, **kwargs):
  34. """Serialize a NotebookNode object as a JSON string"""
  35. kwargs["cls"] = BytesEncoder
  36. kwargs["indent"] = 1
  37. kwargs["sort_keys"] = True
  38. kwargs["separators"] = (",", ": ")
  39. kwargs.setdefault("ensure_ascii", False)
  40. # don't modify in-memory dict
  41. nb = copy.deepcopy(nb)
  42. if kwargs.pop("split_lines", True):
  43. nb = split_lines(nb)
  44. nb = strip_transient(nb)
  45. return json.dumps(nb, **kwargs)
  46. _reader = JSONReader()
  47. _writer = JSONWriter()
  48. reads = _reader.reads
  49. read = _reader.read
  50. to_notebook = _reader.to_notebook
  51. write = _writer.write
  52. writes = _writer.writes