Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbformat/v4/nbjson.py: 47%
38 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
1"""Read and write notebooks in JSON format."""
3# Copyright (c) IPython Development Team.
4# Distributed under the terms of the Modified BSD License.
6import copy
7import json
9from nbformat.notebooknode import from_dict
11from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, split_lines, strip_transient
14class BytesEncoder(json.JSONEncoder):
15 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
17 def default(self, obj):
18 """Get the default value of an object."""
19 if isinstance(obj, bytes):
20 return obj.decode("ascii")
21 return json.JSONEncoder.default(self, obj)
24class JSONReader(NotebookReader):
25 """A JSON notebook reader."""
27 def reads(self, s, **kwargs):
28 """Read a JSON string into a Notebook object"""
29 nb = json.loads(s, **kwargs)
30 nb = self.to_notebook(nb, **kwargs)
31 return nb
33 def to_notebook(self, d, **kwargs):
34 """Convert a disk-format notebook dict to in-memory NotebookNode
36 handles multi-line values as strings, scrubbing of transient values, etc.
37 """
38 nb = from_dict(d)
39 nb = rejoin_lines(nb)
40 nb = strip_transient(nb)
41 return nb
44class JSONWriter(NotebookWriter):
45 """A JSON notebook writer."""
47 def writes(self, nb, **kwargs):
48 """Serialize a NotebookNode object as a JSON string"""
49 kwargs["cls"] = BytesEncoder
50 kwargs["indent"] = 1
51 kwargs["sort_keys"] = True
52 kwargs["separators"] = (",", ": ")
53 kwargs.setdefault("ensure_ascii", False)
54 # don't modify in-memory dict
55 nb = copy.deepcopy(nb)
56 if kwargs.pop("split_lines", True):
57 nb = split_lines(nb)
58 nb = strip_transient(nb)
59 return json.dumps(nb, **kwargs)
62_reader = JSONReader()
63_writer = JSONWriter()
65reads = _reader.reads
66read = _reader.read
67to_notebook = _reader.to_notebook
68write = _writer.write
69writes = _writer.writes