Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nbformat/v2/nbjson.py: 61%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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# -----------------------------------------------------------------------------
18from __future__ import annotations
20import copy
21import json
23from .nbbase import from_dict
24from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, restore_bytes, split_lines
26# -----------------------------------------------------------------------------
27# Code
28# -----------------------------------------------------------------------------
31class BytesEncoder(json.JSONEncoder):
32 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
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)
41class JSONReader(NotebookReader):
42 """A JSON notebook reader."""
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
50 def to_notebook(self, d, **kwargs):
51 """Convert a string to a notebook."""
52 return restore_bytes(rejoin_lines(from_dict(d)))
55class JSONWriter(NotebookWriter):
56 """A JSON notebook writer."""
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)
68_reader = JSONReader()
69_writer = JSONWriter()
71reads = _reader.reads
72read = _reader.read
73to_notebook = _reader.to_notebook
74write = _writer.write
75writes = _writer.writes