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