##// END OF EJS Templates
sort keys when writing json notebooks
MinRK -
Show More
@@ -1,62 +1,63 b''
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 from .nbbase import from_dict
20 20 from .rwbase import NotebookReader, NotebookWriter, restore_bytes
21 21 import json
22 22
23 23 #-----------------------------------------------------------------------------
24 24 # Code
25 25 #-----------------------------------------------------------------------------
26 26
27 27 class BytesEncoder(json.JSONEncoder):
28 28 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
29 29 def default(self, obj):
30 30 if isinstance(obj, bytes):
31 31 return obj.decode('ascii')
32 32 return json.JSONEncoder.default(self, obj)
33 33
34 34
35 35 class JSONReader(NotebookReader):
36 36
37 37 def reads(self, s, **kwargs):
38 38 nb = json.loads(s, **kwargs)
39 39 nb = self.to_notebook(nb, **kwargs)
40 40 return nb
41 41
42 42 def to_notebook(self, d, **kwargs):
43 43 return restore_bytes(from_dict(d))
44 44
45 45
46 46 class JSONWriter(NotebookWriter):
47 47
48 48 def writes(self, nb, **kwargs):
49 49 kwargs['cls'] = BytesEncoder
50 50 kwargs['indent'] = 4
51 kwargs['sort_keys'] = True
51 52 return json.dumps(nb, **kwargs)
52 53
53 54
54 55 _reader = JSONReader()
55 56 _writer = JSONWriter()
56 57
57 58 reads = _reader.reads
58 59 read = _reader.read
59 60 to_notebook = _reader.to_notebook
60 61 write = _writer.write
61 62 writes = _writer.writes
62 63
General Comments 0
You need to be logged in to leave comments. Login now