1"""Read and write notebooks in JSON format.
2
3Authors:
4
5* Brian Granger
6"""
7
8# -----------------------------------------------------------------------------
9# Copyright (C) 2008-2011 The IPython Development Team
10#
11# Distributed under the terms of the BSD License. The full license is in
12# the file LICENSE, distributed as part of this software.
13# -----------------------------------------------------------------------------
14
15# -----------------------------------------------------------------------------
16# Imports
17# -----------------------------------------------------------------------------
18from __future__ import annotations
19
20import copy
21import json
22
23from .nbbase import from_dict
24from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, restore_bytes, split_lines
25
26# -----------------------------------------------------------------------------
27# Code
28# -----------------------------------------------------------------------------
29
30
31class BytesEncoder(json.JSONEncoder):
32 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
33
34 def default(self, obj):
35 """The default value of an object."""
36 if isinstance(obj, bytes):
37 return obj.decode("ascii")
38 return json.JSONEncoder.default(self, obj)
39
40
41class JSONReader(NotebookReader):
42 """A JSON notebook reader."""
43
44 def reads(self, s, **kwargs):
45 """Convert a string to a notebook."""
46 nb = json.loads(s, **kwargs)
47 nb = self.to_notebook(nb, **kwargs)
48 return nb # noqa: RET504
49
50 def to_notebook(self, d, **kwargs):
51 """Convert a string to a notebook."""
52 return restore_bytes(rejoin_lines(from_dict(d)))
53
54
55class JSONWriter(NotebookWriter):
56 """A JSON notebook writer."""
57
58 def writes(self, nb, **kwargs):
59 """Convert a notebook object to a string."""
60 kwargs["cls"] = BytesEncoder
61 kwargs["indent"] = 1
62 kwargs["sort_keys"] = True
63 if kwargs.pop("split_lines", True):
64 nb = split_lines(copy.deepcopy(nb))
65 return json.dumps(nb, **kwargs)
66
67
68_reader = JSONReader()
69_writer = JSONWriter()
70
71reads = _reader.reads
72read = _reader.read
73to_notebook = _reader.to_notebook
74write = _writer.write
75writes = _writer.writes