Debian Codegraph @

lib-python/3/json/encoder.py

raw symbols SCIP
1 """Implementation of JSONEncoder
2 """
3 import re
4
5 try:
6 from _json import encode_basestring_ascii as c_encode_basestring_ascii
7 except ImportError:
8 c_encode_basestring_ascii = None
9 try:
10 from _json import encode_basestring as c_encode_basestring
11 except ImportError:
12 c_encode_basestring = None
13 try:
14 from _json import make_encoder as c_make_encoder
15 except ImportError:
16 try:
17 from _pypyjson import make_encoder as c_make_encoder
18 except ImportError:
19 c_make_encoder = None
20
21 ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
22 ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
23 HAS_UTF8 = re.compile(b'[\x80-\xff]')
24 ESCAPE_DCT = {
25 '\\': '\\\\',
26 '"': '\\"',
27 '\b': '\\b',
28 '\f': '\\f',
29 '\n': '\\n',
30 '\r': '\\r',
31 '\t': '\\t',
32 }
33 for i in range(0x20):
34 ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
35 #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
36 del i
37
38 INFINITY = float('inf')
39
40 def py_encode_basestring(s):
41 """Return a JSON representation of a Python string
42
43 """
44 def replace(match):
45 return ESCAPE_DCT[match.group(0)]
46 return '"' + ESCAPE.sub(replace, s) + '"'
47
48
49 encode_basestring = (c_encode_basestring or py_encode_basestring)
50
51
52 def py_encode_basestring_ascii(s):
53 """Return an ASCII-only JSON representation of a Python string
54
55 """
56 def replace(match):
57 s = match.group(0)
58 try:
59 return ESCAPE_DCT[s]
60 except KeyError:
61 n = ord(s)
62 if n < 0x10000:
63 return '\\u{0:04x}'.format(n)
64 #return '\\u%04x' % (n,)
65 else:
66 # surrogate pair
67 n -= 0x10000
68 s1 = 0xd800 | ((n >> 10) & 0x3ff)
69 s2 = 0xdc00 | (n & 0x3ff)
70 return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
71 return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
72
73
74 encode_basestring_ascii = (
75 c_encode_basestring_ascii or py_encode_basestring_ascii)
76
77 class JSONEncoder(object):
78 """Extensible JSON <https://json.org> encoder for Python data structures.
79
80 Supports the following objects and types by default:
81
82 +-------------------+---------------+
83 | Python | JSON |
84 +===================+===============+
85 | dict | object |
86 +-------------------+---------------+
87 | list, tuple | array |
88 +-------------------+---------------+
89 | str | string |
90 +-------------------+---------------+
91 | int, float | number |
92 +-------------------+---------------+
93 | True | true |
94 +-------------------+---------------+
95 | False | false |
96 +-------------------+---------------+
97 | None | null |
98 +-------------------+---------------+
99
100 To extend this to recognize other objects, subclass and implement a
101 ``.default()`` method with another method that returns a serializable
102 object for ``o`` if possible, otherwise it should call the superclass
103 implementation (to raise ``TypeError``).
104
105 """
106 item_separator = ', '
107 key_separator = ': '
108 def __init__(self, *, skipkeys=False, ensure_ascii=True,
109 check_circular=True, allow_nan=True, sort_keys=False,
110 indent=None, separators=None, default=None):
111 """Constructor for JSONEncoder, with sensible defaults.
112
113 If skipkeys is false, then it is a TypeError to attempt
114 encoding of keys that are not str, int, float or None. If
115 skipkeys is True, such items are simply skipped.
116
117 If ensure_ascii is true, the output is guaranteed to be str
118 objects with all incoming non-ASCII characters escaped. If
119 ensure_ascii is false, the output can contain non-ASCII characters.
120
121 If check_circular is true, then lists, dicts, and custom encoded
122 objects will be checked for circular references during encoding to
123 prevent an infinite recursion (which would cause an RecursionError).
124 Otherwise, no such check takes place.
125
126 If allow_nan is true, then NaN, Infinity, and -Infinity will be
127 encoded as such. This behavior is not JSON specification compliant,
128 but is consistent with most JavaScript based encoders and decoders.
129 Otherwise, it will be a ValueError to encode such floats.
130
131 If sort_keys is true, then the output of dictionaries will be
132 sorted by key; this is useful for regression tests to ensure
133 that JSON serializations can be compared on a day-to-day basis.
134
135 If indent is a non-negative integer, then JSON array
136 elements and object members will be pretty-printed with that
137 indent level. An indent level of 0 will only insert newlines.
138 None is the most compact representation.
139
140 If specified, separators should be an (item_separator, key_separator)
141 tuple. The default is (', ', ': ') if *indent* is ``None`` and
142 (',', ': ') otherwise. To get the most compact JSON representation,
143 you should specify (',', ':') to eliminate whitespace.
144
145 If specified, default is a function that gets called for objects
146 that can't otherwise be serialized. It should return a JSON encodable
147 version of the object or raise a ``TypeError``.
148
149 """
150
151 self.skipkeys = skipkeys
152 self.ensure_ascii = ensure_ascii
153 self.check_circular = check_circular
154 self.allow_nan = allow_nan
155 self.sort_keys = sort_keys
156 self.indent = indent
157 if separators is not None:
158 self.item_separator, self.key_separator = separators
159 elif indent is not None:
160 self.item_separator = ','
161 if default is not None:
162 self.default = default
163
164 def default(self, o):
165 """Implement this method in a subclass such that it returns
166 a serializable object for ``o``, or calls the base implementation
167 (to raise a ``TypeError``).
168
169 For example, to support arbitrary iterators, you could
170 implement default like this::
171
172 def default(self, o):
173 try:
174 iterable = iter(o)
175 except TypeError:
176 pass
177 else:
178 return list(iterable)
179 # Let the base class default method raise the TypeError
180 return super().default(o)
181
182 """
183 raise TypeError(f'Object of type {o.__class__.__name__} '
184 f'is not JSON serializable')
185
186 def encode(self, o):
187 """Return a JSON string representation of a Python data structure.
188
189 >>> from json.encoder import JSONEncoder
190 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
191 '{"foo": ["bar", "baz"]}'
192
193 """
194 # This is for extremely simple cases and benchmarks.
195 if isinstance(o, str):
196 if self.ensure_ascii:
197 return encode_basestring_ascii(o)
198 else:
199 return encode_basestring(o)
200 # This doesn't pass the iterator directly to ''.join() because the
201 # exceptions aren't as detailed. The list call should be roughly
202 # equivalent to the PySequence_Fast that ''.join() would do.
203 chunks = self.iterencode(o, _one_shot=True)
204 if not isinstance(chunks, (list, tuple)):
205 chunks = list(chunks)
206 return ''.join(chunks)
207
208 def iterencode(self, o, _one_shot=False):
209 """Encode the given object and yield each string
210 representation as available.
211
212 For example::
213
214 for chunk in JSONEncoder().iterencode(bigobject):
215 mysocket.write(chunk)
216
217 """
218 if self.check_circular:
219 markers = {}
220 else:
221 markers = None
222 if self.ensure_ascii:
223 _encoder = encode_basestring_ascii
224 else:
225 _encoder = encode_basestring
226
227 def floatstr(o, allow_nan=self.allow_nan,
228 _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
229 # Check for specials. Note that this type of test is processor
230 # and/or platform-specific, so do tests which don't depend on the
231 # internals.
232
233 if o != o:
234 text = 'NaN'
235 elif o == _inf:
236 text = 'Infinity'
237 elif o == _neginf:
238 text = '-Infinity'
239 else:
240 return _repr(o)
241
242 if not allow_nan:
243 raise ValueError(
244 "Out of range float values are not JSON compliant: " +
245 repr(o))
246
247 return text
248
249
250 if (_one_shot and c_make_encoder is not None
251 and self.indent is None):
252 _iterencode = c_make_encoder(
253 markers, self.default, _encoder, self.indent,
254 self.key_separator, self.item_separator, self.sort_keys,
255 self.skipkeys, self.allow_nan)
256 else:
257 _iterencode = _make_iterencode(
258 markers, self.default, _encoder, self.indent, floatstr,
259 self.key_separator, self.item_separator, self.sort_keys,
260 self.skipkeys, _one_shot)
261 return _iterencode(o, 0)
262
263 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
264 _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
265 ## HACK: hand-optimized bytecode; turn globals into locals
266 ValueError=ValueError,
267 dict=dict,
268 float=float,
269 id=id,
270 int=int,
271 isinstance=isinstance,
272 list=list,
273 str=str,
274 tuple=tuple,
275 _intstr=int.__repr__,
276 ):
277
278 if _indent is not None and not isinstance(_indent, str):
279 _indent = ' ' * _indent
280
281 def _iterencode_list(lst, _current_indent_level):
282 if not lst:
283 yield '[]'
284 return
285 if markers is not None:
286 markerid = id(lst)
287 if markerid in markers:
288 raise ValueError("Circular reference detected")
289 markers[markerid] = lst
290 buf = '['
291 if _indent is not None:
292 _current_indent_level += 1
293 newline_indent = '\n' + _indent * _current_indent_level
294 separator = _item_separator + newline_indent
295 buf += newline_indent
296 else:
297 newline_indent = None
298 separator = _item_separator
299 first = True
300 for value in lst:
301 if first:
302 first = False
303 else:
304 buf = separator
305 if isinstance(value, str):
306 yield buf + _encoder(value)
307 elif value is None:
308 yield buf + 'null'
309 elif value is True:
310 yield buf + 'true'
311 elif value is False:
312 yield buf + 'false'
313 elif isinstance(value, int):
314 # Subclasses of int/float may override __repr__, but we still
315 # want to encode them as integers/floats in JSON. One example
316 # within the standard library is IntEnum.
317 yield buf + _intstr(value)
318 elif isinstance(value, float):
319 # see comment above for int
320 yield buf + _floatstr(value)
321 else:
322 yield buf
323 if isinstance(value, (list, tuple)):
324 chunks = _iterencode_list(value, _current_indent_level)
325 elif isinstance(value, dict):
326 chunks = _iterencode_dict(value, _current_indent_level)
327 else:
328 chunks = _iterencode(value, _current_indent_level)
329 yield from chunks
330 if newline_indent is not None:
331 _current_indent_level -= 1
332 yield '\n' + _indent * _current_indent_level
333 yield ']'
334 if markers is not None:
335 del markers[markerid]
336
337 def _iterencode_dict(dct, _current_indent_level):
338 if not dct:
339 yield '{}'
340 return
341 if markers is not None:
342 markerid = id(dct)
343 if markerid in markers:
344 raise ValueError("Circular reference detected")
345 markers[markerid] = dct
346 yield '{'
347 if _indent is not None:
348 _current_indent_level += 1
349 newline_indent = '\n' + _indent * _current_indent_level
350 item_separator = _item_separator + newline_indent
351 yield newline_indent
352 else:
353 newline_indent = None
354 item_separator = _item_separator
355 first = True
356 if _sort_keys:
357 items = sorted(dct.items())
358 else:
359 items = dct.items()
360 for key, value in items:
361 if isinstance(key, str):
362 pass
363 # JavaScript is weakly typed for these, so it makes sense to
364 # also allow them. Many encoders seem to do something like this.
365 elif isinstance(key, float):
366 # see comment for int/float in _make_iterencode
367 key = _floatstr(key)
368 elif key is True:
369 key = 'true'
370 elif key is False:
371 key = 'false'
372 elif key is None:
373 key = 'null'
374 elif isinstance(key, int):
375 # see comment for int/float in _make_iterencode
376 key = _intstr(key)
377 elif _skipkeys:
378 continue
379 else:
380 raise TypeError(f'keys must be str, int, float, bool or None, '
381 f'not {key.__class__.__name__}')
382 if first:
383 first = False
384 else:
385 yield item_separator
386 yield _encoder(key)
387 yield _key_separator
388 if isinstance(value, str):
389 yield _encoder(value)
390 elif value is None:
391 yield 'null'
392 elif value is True:
393 yield 'true'
394 elif value is False:
395 yield 'false'
396 elif isinstance(value, int):
397 # see comment for int/float in _make_iterencode
398 yield _intstr(value)
399 elif isinstance(value, float):
400 # see comment for int/float in _make_iterencode
401 yield _floatstr(value)
402 else:
403 if isinstance(value, (list, tuple)):
404 chunks = _iterencode_list(value, _current_indent_level)
405 elif isinstance(value, dict):
406 chunks = _iterencode_dict(value, _current_indent_level)
407 else:
408 chunks = _iterencode(value, _current_indent_level)
409 yield from chunks
410 if newline_indent is not None:
411 _current_indent_level -= 1
412 yield '\n' + _indent * _current_indent_level
413 yield '}'
414 if markers is not None:
415 del markers[markerid]
416
417 def _iterencode(o, _current_indent_level):
418 if isinstance(o, str):
419 yield _encoder(o)
420 elif o is None:
421 yield 'null'
422 elif o is True:
423 yield 'true'
424 elif o is False:
425 yield 'false'
426 elif isinstance(o, int):
427 # see comment for int/float in _make_iterencode
428 yield _intstr(o)
429 elif isinstance(o, float):
430 # see comment for int/float in _make_iterencode
431 yield _floatstr(o)
432 elif isinstance(o, (list, tuple)):
433 yield from _iterencode_list(o, _current_indent_level)
434 elif isinstance(o, dict):
435 yield from _iterencode_dict(o, _current_indent_level)
436 else:
437 if markers is not None:
438 markerid = id(o)
439 if markerid in markers:
440 raise ValueError("Circular reference detected")
441 markers[markerid] = o
442 o = _default(o)
443 yield from _iterencode(o, _current_indent_level)
444 if markers is not None:
445 del markers[markerid]
446 return _iterencode