##// END OF EJS Templates
nbjson.writes always returns unicode
MinRK -
Show More
@@ -1,70 +1,72 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 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 from IPython.utils import py3compat
28
27 29 #-----------------------------------------------------------------------------
28 30 # Code
29 31 #-----------------------------------------------------------------------------
30 32
31 33 class BytesEncoder(json.JSONEncoder):
32 34 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings."""
33 35 def default(self, obj):
34 36 if isinstance(obj, bytes):
35 37 return obj.decode('ascii')
36 38 return json.JSONEncoder.default(self, obj)
37 39
38 40
39 41 class JSONReader(NotebookReader):
40 42
41 43 def reads(self, s, **kwargs):
42 44 nb = json.loads(s, **kwargs)
43 45 nb = self.to_notebook(nb, **kwargs)
44 46 return nb
45 47
46 48 def to_notebook(self, d, **kwargs):
47 49 return restore_bytes(rejoin_lines(from_dict(d)))
48 50
49 51
50 52 class JSONWriter(NotebookWriter):
51 53
52 54 def writes(self, nb, **kwargs):
53 55 kwargs['cls'] = BytesEncoder
54 56 kwargs['indent'] = 1
55 57 kwargs['sort_keys'] = True
56 58 kwargs['separators'] = (',',': ')
57 59 if kwargs.pop('split_lines', True):
58 60 nb = split_lines(copy.deepcopy(nb))
59 return json.dumps(nb, **kwargs)
61 return py3compat.str_to_unicode(json.dumps(nb, **kwargs), 'utf-8')
60 62
61 63
62 64 _reader = JSONReader()
63 65 _writer = JSONWriter()
64 66
65 67 reads = _reader.reads
66 68 read = _reader.read
67 69 to_notebook = _reader.to_notebook
68 70 write = _writer.write
69 71 writes = _writer.writes
70 72
General Comments 0
You need to be logged in to leave comments. Login now