Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbformat/v2/nbjson.py: 58%
31 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.
3Authors:
5* Brian Granger
6"""
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# -----------------------------------------------------------------------------
15# -----------------------------------------------------------------------------
16# Imports
17# -----------------------------------------------------------------------------
19import copy
20import json
22from .nbbase import from_dict
23from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, restore_bytes, split_lines
25# -----------------------------------------------------------------------------
26# Code
27# -----------------------------------------------------------------------------
30class BytesEncoder(json.JSONEncoder):
31 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
33 def default(self, obj):
34 """The default value of an object."""
35 if isinstance(obj, bytes):
36 return obj.decode("ascii")
37 return json.JSONEncoder.default(self, obj)
40class JSONReader(NotebookReader):
41 """A JSON notebook reader."""
43 def reads(self, s, **kwargs):
44 """Convert a string to a notebook."""
45 nb = json.loads(s, **kwargs)
46 nb = self.to_notebook(nb, **kwargs)
47 return nb
49 def to_notebook(self, d, **kwargs):
50 """Convert a string to a notebook."""
51 return restore_bytes(rejoin_lines(from_dict(d)))
54class JSONWriter(NotebookWriter):
55 """A JSON notebook writer."""
57 def writes(self, nb, **kwargs):
58 """Convert a notebook object to a string."""
59 kwargs["cls"] = BytesEncoder
60 kwargs["indent"] = 1
61 kwargs["sort_keys"] = True
62 if kwargs.pop("split_lines", True):
63 nb = split_lines(copy.deepcopy(nb))
64 return json.dumps(nb, **kwargs)
67_reader = JSONReader()
68_writer = JSONWriter()
70reads = _reader.reads
71read = _reader.read
72to_notebook = _reader.to_notebook
73write = _writer.write
74writes = _writer.writes