blob: 26e9eb2bc69255a400a3c48686a1f821cab562db [file] [log] [blame]
Christian Heimes90540002008-05-08 14:29:10 +00001"""Implementation of JSONEncoder
2"""
Christian Heimes90540002008-05-08 14:29:10 +00003import re
4
5try:
6 from _json import encode_basestring_ascii as c_encode_basestring_ascii
Brett Cannoncd171c82013-07-04 17:43:24 -04007except ImportError:
Christian Heimes90540002008-05-08 14:29:10 +00008 c_encode_basestring_ascii = None
Benjamin Petersonc6b607d2009-05-02 12:36:44 +00009try:
Antoine Pitroudc3eaa82015-01-11 16:41:01 +010010 from _json import encode_basestring as c_encode_basestring
11except ImportError:
12 c_encode_basestring = None
13try:
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000014 from _json import make_encoder as c_make_encoder
Brett Cannoncd171c82013-07-04 17:43:24 -040015except ImportError:
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000016 c_make_encoder = None
Christian Heimes90540002008-05-08 14:29:10 +000017
18ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
19ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000020HAS_UTF8 = re.compile(b'[\x80-\xff]')
Christian Heimes90540002008-05-08 14:29:10 +000021ESCAPE_DCT = {
22 '\\': '\\\\',
23 '"': '\\"',
24 '\b': '\\b',
25 '\f': '\\f',
26 '\n': '\\n',
27 '\r': '\\r',
28 '\t': '\\t',
29}
30for i in range(0x20):
31 ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000032 #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
Christian Heimes90540002008-05-08 14:29:10 +000033
Ezio Melotti898d51d2012-05-21 17:49:06 -060034INFINITY = float('inf')
Christian Heimes90540002008-05-08 14:29:10 +000035FLOAT_REPR = repr
36
Antoine Pitroudc3eaa82015-01-11 16:41:01 +010037def py_encode_basestring(s):
Christian Heimes90540002008-05-08 14:29:10 +000038 """Return a JSON representation of a Python string
39
40 """
41 def replace(match):
42 return ESCAPE_DCT[match.group(0)]
43 return '"' + ESCAPE.sub(replace, s) + '"'
44
45
Antoine Pitroudc3eaa82015-01-11 16:41:01 +010046encode_basestring = (c_encode_basestring or py_encode_basestring)
47
48
Christian Heimes90540002008-05-08 14:29:10 +000049def py_encode_basestring_ascii(s):
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000050 """Return an ASCII-only JSON representation of a Python string
51
52 """
Christian Heimes90540002008-05-08 14:29:10 +000053 def replace(match):
54 s = match.group(0)
55 try:
56 return ESCAPE_DCT[s]
57 except KeyError:
58 n = ord(s)
59 if n < 0x10000:
60 return '\\u{0:04x}'.format(n)
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000061 #return '\\u%04x' % (n,)
Christian Heimes90540002008-05-08 14:29:10 +000062 else:
63 # surrogate pair
64 n -= 0x10000
65 s1 = 0xd800 | ((n >> 10) & 0x3ff)
66 s2 = 0xdc00 | (n & 0x3ff)
67 return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000068 return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
Christian Heimes90540002008-05-08 14:29:10 +000069
70
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000071encode_basestring_ascii = (
72 c_encode_basestring_ascii or py_encode_basestring_ascii)
Christian Heimes90540002008-05-08 14:29:10 +000073
74class JSONEncoder(object):
75 """Extensible JSON <http://json.org> encoder for Python data structures.
76
77 Supports the following objects and types by default:
78
79 +-------------------+---------------+
80 | Python | JSON |
81 +===================+===============+
82 | dict | object |
83 +-------------------+---------------+
84 | list, tuple | array |
85 +-------------------+---------------+
Georg Brandlc8284cf2010-08-02 20:16:18 +000086 | str | string |
Christian Heimes90540002008-05-08 14:29:10 +000087 +-------------------+---------------+
Georg Brandlc8284cf2010-08-02 20:16:18 +000088 | int, float | number |
Christian Heimes90540002008-05-08 14:29:10 +000089 +-------------------+---------------+
90 | True | true |
91 +-------------------+---------------+
92 | False | false |
93 +-------------------+---------------+
94 | None | null |
95 +-------------------+---------------+
96
97 To extend this to recognize other objects, subclass and implement a
98 ``.default()`` method with another method that returns a serializable
99 object for ``o`` if possible, otherwise it should call the superclass
100 implementation (to raise ``TypeError``).
101
102 """
Christian Heimes90540002008-05-08 14:29:10 +0000103 item_separator = ', '
104 key_separator = ': '
105 def __init__(self, skipkeys=False, ensure_ascii=True,
106 check_circular=True, allow_nan=True, sort_keys=False,
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000107 indent=None, separators=None, default=None):
Christian Heimes90540002008-05-08 14:29:10 +0000108 """Constructor for JSONEncoder, with sensible defaults.
109
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000110 If skipkeys is false, then it is a TypeError to attempt
Georg Brandlc8284cf2010-08-02 20:16:18 +0000111 encoding of keys that are not str, int, float or None. If
Christian Heimes90540002008-05-08 14:29:10 +0000112 skipkeys is True, such items are simply skipped.
113
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000114 If ensure_ascii is true, the output is guaranteed to be str
Georg Brandlc8284cf2010-08-02 20:16:18 +0000115 objects with all incoming non-ASCII characters escaped. If
116 ensure_ascii is false, the output can contain non-ASCII characters.
Christian Heimes90540002008-05-08 14:29:10 +0000117
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000118 If check_circular is true, then lists, dicts, and custom encoded
Christian Heimes90540002008-05-08 14:29:10 +0000119 objects will be checked for circular references during encoding to
120 prevent an infinite recursion (which would cause an OverflowError).
121 Otherwise, no such check takes place.
122
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000123 If allow_nan is true, then NaN, Infinity, and -Infinity will be
Christian Heimes90540002008-05-08 14:29:10 +0000124 encoded as such. This behavior is not JSON specification compliant,
125 but is consistent with most JavaScript based encoders and decoders.
126 Otherwise, it will be a ValueError to encode such floats.
127
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000128 If sort_keys is true, then the output of dictionaries will be
Christian Heimes90540002008-05-08 14:29:10 +0000129 sorted by key; this is useful for regression tests to ensure
130 that JSON serializations can be compared on a day-to-day basis.
131
132 If indent is a non-negative integer, then JSON array
133 elements and object members will be pretty-printed with that
134 indent level. An indent level of 0 will only insert newlines.
135 None is the most compact representation.
136
Ezio Melotti10031442012-11-29 00:42:56 +0200137 If specified, separators should be an (item_separator, key_separator)
138 tuple. The default is (', ', ': ') if *indent* is ``None`` and
139 (',', ': ') otherwise. To get the most compact JSON representation,
140 you should specify (',', ':') to eliminate whitespace.
Christian Heimes90540002008-05-08 14:29:10 +0000141
142 If specified, default is a function that gets called for objects
143 that can't otherwise be serialized. It should return a JSON encodable
144 version of the object or raise a ``TypeError``.
145
Christian Heimes90540002008-05-08 14:29:10 +0000146 """
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000147
Christian Heimes90540002008-05-08 14:29:10 +0000148 self.skipkeys = skipkeys
149 self.ensure_ascii = ensure_ascii
150 self.check_circular = check_circular
151 self.allow_nan = allow_nan
152 self.sort_keys = sort_keys
153 self.indent = indent
Christian Heimes90540002008-05-08 14:29:10 +0000154 if separators is not None:
155 self.item_separator, self.key_separator = separators
Ezio Melotti10031442012-11-29 00:42:56 +0200156 elif indent is not None:
157 self.item_separator = ','
Christian Heimes90540002008-05-08 14:29:10 +0000158 if default is not None:
159 self.default = default
Christian Heimes90540002008-05-08 14:29:10 +0000160
161 def default(self, o):
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000162 """Implement this method in a subclass such that it returns
163 a serializable object for ``o``, or calls the base implementation
164 (to raise a ``TypeError``).
Christian Heimes90540002008-05-08 14:29:10 +0000165
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000166 For example, to support arbitrary iterators, you could
167 implement default like this::
Christian Heimes90540002008-05-08 14:29:10 +0000168
169 def default(self, o):
170 try:
171 iterable = iter(o)
172 except TypeError:
173 pass
174 else:
175 return list(iterable)
R David Murraydd246172013-03-17 21:52:35 -0400176 # Let the base class default method raise the TypeError
Christian Heimes90540002008-05-08 14:29:10 +0000177 return JSONEncoder.default(self, o)
178
179 """
180 raise TypeError(repr(o) + " is not JSON serializable")
181
182 def encode(self, o):
183 """Return a JSON string representation of a Python data structure.
184
Ethan Furmana4998a72013-08-10 13:01:45 -0700185 >>> from json.encoder import JSONEncoder
Christian Heimes90540002008-05-08 14:29:10 +0000186 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
187 '{"foo": ["bar", "baz"]}'
188
189 """
190 # This is for extremely simple cases and benchmarks.
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000191 if isinstance(o, str):
Christian Heimes90540002008-05-08 14:29:10 +0000192 if self.ensure_ascii:
193 return encode_basestring_ascii(o)
194 else:
195 return encode_basestring(o)
196 # This doesn't pass the iterator directly to ''.join() because the
197 # exceptions aren't as detailed. The list call should be roughly
198 # equivalent to the PySequence_Fast that ''.join() would do.
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000199 chunks = self.iterencode(o, _one_shot=True)
200 if not isinstance(chunks, (list, tuple)):
201 chunks = list(chunks)
Christian Heimes90540002008-05-08 14:29:10 +0000202 return ''.join(chunks)
203
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000204 def iterencode(self, o, _one_shot=False):
205 """Encode the given object and yield each string
206 representation as available.
Christian Heimes90540002008-05-08 14:29:10 +0000207
208 For example::
209
210 for chunk in JSONEncoder().iterencode(bigobject):
211 mysocket.write(chunk)
212
213 """
214 if self.check_circular:
215 markers = {}
216 else:
217 markers = None
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000218 if self.ensure_ascii:
219 _encoder = encode_basestring_ascii
220 else:
221 _encoder = encode_basestring
222
223 def floatstr(o, allow_nan=self.allow_nan,
224 _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
225 # Check for specials. Note that this type of test is processor
226 # and/or platform-specific, so do tests which don't depend on the
227 # internals.
228
229 if o != o:
230 text = 'NaN'
231 elif o == _inf:
232 text = 'Infinity'
233 elif o == _neginf:
234 text = '-Infinity'
235 else:
236 return _repr(o)
237
238 if not allow_nan:
239 raise ValueError(
240 "Out of range float values are not JSON compliant: " +
241 repr(o))
242
243 return text
244
245
246 if (_one_shot and c_make_encoder is not None
R David Murray3dd02d62011-04-12 21:02:45 -0400247 and self.indent is None):
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000248 _iterencode = c_make_encoder(
249 markers, self.default, _encoder, self.indent,
250 self.key_separator, self.item_separator, self.sort_keys,
251 self.skipkeys, self.allow_nan)
252 else:
253 _iterencode = _make_iterencode(
254 markers, self.default, _encoder, self.indent, floatstr,
255 self.key_separator, self.item_separator, self.sort_keys,
256 self.skipkeys, _one_shot)
257 return _iterencode(o, 0)
258
259def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
260 _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
261 ## HACK: hand-optimized bytecode; turn globals into locals
262 ValueError=ValueError,
263 dict=dict,
264 float=float,
265 id=id,
266 int=int,
267 isinstance=isinstance,
268 list=list,
269 str=str,
270 tuple=tuple,
271 ):
272
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000273 if _indent is not None and not isinstance(_indent, str):
274 _indent = ' ' * _indent
275
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000276 def _iterencode_list(lst, _current_indent_level):
277 if not lst:
278 yield '[]'
279 return
280 if markers is not None:
281 markerid = id(lst)
282 if markerid in markers:
283 raise ValueError("Circular reference detected")
284 markers[markerid] = lst
285 buf = '['
286 if _indent is not None:
287 _current_indent_level += 1
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000288 newline_indent = '\n' + _indent * _current_indent_level
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000289 separator = _item_separator + newline_indent
290 buf += newline_indent
291 else:
292 newline_indent = None
293 separator = _item_separator
294 first = True
295 for value in lst:
296 if first:
297 first = False
298 else:
299 buf = separator
300 if isinstance(value, str):
301 yield buf + _encoder(value)
302 elif value is None:
303 yield buf + 'null'
304 elif value is True:
305 yield buf + 'true'
306 elif value is False:
307 yield buf + 'false'
308 elif isinstance(value, int):
Ethan Furmana4998a72013-08-10 13:01:45 -0700309 # Subclasses of int/float may override __str__, but we still
310 # want to encode them as integers/floats in JSON. One example
311 # within the standard library is IntEnum.
312 yield buf + str(int(value))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000313 elif isinstance(value, float):
Ethan Furmana4998a72013-08-10 13:01:45 -0700314 # see comment above for int
315 yield buf + _floatstr(float(value))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000316 else:
317 yield buf
318 if isinstance(value, (list, tuple)):
319 chunks = _iterencode_list(value, _current_indent_level)
320 elif isinstance(value, dict):
321 chunks = _iterencode_dict(value, _current_indent_level)
322 else:
323 chunks = _iterencode(value, _current_indent_level)
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700324 yield from chunks
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000325 if newline_indent is not None:
326 _current_indent_level -= 1
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000327 yield '\n' + _indent * _current_indent_level
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000328 yield ']'
329 if markers is not None:
330 del markers[markerid]
331
332 def _iterencode_dict(dct, _current_indent_level):
333 if not dct:
334 yield '{}'
335 return
336 if markers is not None:
337 markerid = id(dct)
338 if markerid in markers:
339 raise ValueError("Circular reference detected")
340 markers[markerid] = dct
341 yield '{'
342 if _indent is not None:
343 _current_indent_level += 1
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000344 newline_indent = '\n' + _indent * _current_indent_level
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000345 item_separator = _item_separator + newline_indent
346 yield newline_indent
347 else:
348 newline_indent = None
349 item_separator = _item_separator
350 first = True
351 if _sort_keys:
352 items = sorted(dct.items(), key=lambda kv: kv[0])
353 else:
354 items = dct.items()
355 for key, value in items:
356 if isinstance(key, str):
357 pass
358 # JavaScript is weakly typed for these, so it makes sense to
359 # also allow them. Many encoders seem to do something like this.
360 elif isinstance(key, float):
Ethan Furmana4998a72013-08-10 13:01:45 -0700361 # see comment for int/float in _make_iterencode
362 key = _floatstr(float(key))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000363 elif key is True:
364 key = 'true'
365 elif key is False:
366 key = 'false'
367 elif key is None:
368 key = 'null'
369 elif isinstance(key, int):
Ethan Furmana4998a72013-08-10 13:01:45 -0700370 # see comment for int/float in _make_iterencode
371 key = str(int(key))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000372 elif _skipkeys:
373 continue
374 else:
375 raise TypeError("key " + repr(key) + " is not a string")
376 if first:
377 first = False
378 else:
379 yield item_separator
380 yield _encoder(key)
381 yield _key_separator
382 if isinstance(value, str):
383 yield _encoder(value)
384 elif value is None:
385 yield 'null'
386 elif value is True:
387 yield 'true'
388 elif value is False:
389 yield 'false'
390 elif isinstance(value, int):
Ethan Furmana4998a72013-08-10 13:01:45 -0700391 # see comment for int/float in _make_iterencode
392 yield str(int(value))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000393 elif isinstance(value, float):
Ethan Furmana4998a72013-08-10 13:01:45 -0700394 # see comment for int/float in _make_iterencode
395 yield _floatstr(float(value))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000396 else:
397 if isinstance(value, (list, tuple)):
398 chunks = _iterencode_list(value, _current_indent_level)
399 elif isinstance(value, dict):
400 chunks = _iterencode_dict(value, _current_indent_level)
401 else:
402 chunks = _iterencode(value, _current_indent_level)
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700403 yield from chunks
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000404 if newline_indent is not None:
405 _current_indent_level -= 1
Raymond Hettingerb643ef82010-10-31 08:00:16 +0000406 yield '\n' + _indent * _current_indent_level
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000407 yield '}'
408 if markers is not None:
409 del markers[markerid]
410
411 def _iterencode(o, _current_indent_level):
412 if isinstance(o, str):
413 yield _encoder(o)
414 elif o is None:
415 yield 'null'
416 elif o is True:
417 yield 'true'
418 elif o is False:
419 yield 'false'
Florent Xicluna02ea12b22010-07-28 16:39:41 +0000420 elif isinstance(o, int):
Ethan Furmana4998a72013-08-10 13:01:45 -0700421 # see comment for int/float in _make_iterencode
422 yield str(int(o))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000423 elif isinstance(o, float):
Ethan Furmana4998a72013-08-10 13:01:45 -0700424 # see comment for int/float in _make_iterencode
425 yield _floatstr(float(o))
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000426 elif isinstance(o, (list, tuple)):
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700427 yield from _iterencode_list(o, _current_indent_level)
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000428 elif isinstance(o, dict):
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700429 yield from _iterencode_dict(o, _current_indent_level)
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000430 else:
431 if markers is not None:
432 markerid = id(o)
433 if markerid in markers:
434 raise ValueError("Circular reference detected")
435 markers[markerid] = o
436 o = _default(o)
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700437 yield from _iterencode(o, _current_indent_level)
Benjamin Petersonc6b607d2009-05-02 12:36:44 +0000438 if markers is not None:
439 del markers[markerid]
440 return _iterencode