Show More
@@ -1,67 +1,68 | |||
|
1 | 1 | """Read and write notebooks in JSON format.""" |
|
2 | 2 | |
|
3 | 3 | # Copyright (c) IPython Development Team. |
|
4 | 4 | # Distributed under the terms of the Modified BSD License. |
|
5 | 5 | |
|
6 | 6 | import copy |
|
7 | 7 | import json |
|
8 | 8 | |
|
9 | 9 | from IPython.utils import py3compat |
|
10 | 10 | |
|
11 | 11 | from .nbbase import from_dict |
|
12 | 12 | from .rwbase import ( |
|
13 | 13 | NotebookReader, NotebookWriter, rejoin_lines, split_lines, strip_transient |
|
14 | 14 | ) |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | class BytesEncoder(json.JSONEncoder): |
|
18 | 18 | """A JSON encoder that accepts b64 (and other *ascii*) bytestrings.""" |
|
19 | 19 | def default(self, obj): |
|
20 | 20 | if isinstance(obj, bytes): |
|
21 | 21 | return obj.decode('ascii') |
|
22 | 22 | return json.JSONEncoder.default(self, obj) |
|
23 | 23 | |
|
24 | 24 | |
|
25 | 25 | class JSONReader(NotebookReader): |
|
26 | 26 | |
|
27 | 27 | def reads(self, s, **kwargs): |
|
28 | 28 | """Read a JSON string into a Notebook object""" |
|
29 | 29 | nb = json.loads(s, **kwargs) |
|
30 | 30 | nb = self.to_notebook(nb, **kwargs) |
|
31 | 31 | return nb |
|
32 | 32 | |
|
33 | 33 | def to_notebook(self, d, **kwargs): |
|
34 | 34 | """Convert a disk-format notebook dict to in-memory NotebookNode |
|
35 | 35 | |
|
36 | 36 | handles multi-line values as strings, scrubbing of transient values, etc. |
|
37 | 37 | """ |
|
38 | 38 | nb = from_dict(d) |
|
39 | 39 | nb = rejoin_lines(nb) |
|
40 | 40 | nb = strip_transient(nb) |
|
41 | 41 | return nb |
|
42 | 42 | |
|
43 | 43 | |
|
44 | 44 | class JSONWriter(NotebookWriter): |
|
45 | 45 | |
|
46 | 46 | def writes(self, nb, **kwargs): |
|
47 | 47 | """Serialize a NotebookNode object as a JSON string""" |
|
48 | 48 | kwargs['cls'] = BytesEncoder |
|
49 | 49 | kwargs['indent'] = 1 |
|
50 | 50 | kwargs['sort_keys'] = True |
|
51 | 51 | kwargs['separators'] = (',',': ') |
|
52 | kwargs.setdefault('ensure_ascii', False) | |
|
52 | 53 | # don't modify in-memory dict |
|
53 | 54 | nb = copy.deepcopy(nb) |
|
54 | 55 | if kwargs.pop('split_lines', True): |
|
55 | 56 | nb = split_lines(nb) |
|
56 | 57 | nb = strip_transient(nb) |
|
57 | 58 | return py3compat.str_to_unicode(json.dumps(nb, **kwargs), 'utf-8') |
|
58 | 59 | |
|
59 | 60 | |
|
60 | 61 | _reader = JSONReader() |
|
61 | 62 | _writer = JSONWriter() |
|
62 | 63 | |
|
63 | 64 | reads = _reader.reads |
|
64 | 65 | read = _reader.read |
|
65 | 66 | to_notebook = _reader.to_notebook |
|
66 | 67 | write = _writer.write |
|
67 | 68 | writes = _writer.writes |
General Comments 0
You need to be logged in to leave comments.
Login now