Aestate
encoder.py
Go to the documentation of this file.
1 """Implementation of JSONEncoder
2 """
3 from __future__ import absolute_import
4 import re
5 from operator import itemgetter
6 # Do not import Decimal directly to avoid reload issues
7 import decimal
8 from .compat import unichr, binary_type, text_type, string_types, integer_types, PY3
10  try:
11  from . import _speedups
12  return _speedups.encode_basestring_ascii, _speedups.make_encoder
13  except ImportError:
14  return None, None
15 c_encode_basestring_ascii, c_make_encoder = _import_speedups()
16 
17 from .decoder import PosInf
18 from .raw_json import RawJSON
19 
20 ESCAPE = re.compile(r'[\x00-\x1f\\"]')
21 ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
22 HAS_UTF8 = re.compile(r'[\x80-\xff]')
23 ESCAPE_DCT = {
24  '\\': '\\\\',
25  '"': '\\"',
26  '\b': '\\b',
27  '\f': '\\f',
28  '\n': '\\n',
29  '\r': '\\r',
30  '\t': '\\t',
31 }
32 for i in range(0x20):
33  #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
34  ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
35 
36 FLOAT_REPR = repr
37 
38 def encode_basestring(s, _PY3=PY3, _q=u'"'):
39  """Return a JSON representation of a Python string
40 
41  """
42  if _PY3:
43  if isinstance(s, bytes):
44  s = str(s, 'utf-8')
45  elif type(s) is not str:
46  # convert an str subclass instance to exact str
47  # raise a TypeError otherwise
48  s = str.__str__(s)
49  else:
50  if isinstance(s, str) and HAS_UTF8.search(s) is not None:
51  s = unicode(s, 'utf-8')
52  elif type(s) not in (str, unicode):
53  # convert an str subclass instance to exact str
54  # convert a unicode subclass instance to exact unicode
55  # raise a TypeError otherwise
56  if isinstance(s, str):
57  s = str.__str__(s)
58  else:
59  s = unicode.__getnewargs__(s)[0]
60  def replace(match):
61  return ESCAPE_DCT[match.group(0)]
62  return _q + ESCAPE.sub(replace, s) + _q
63 
64 
65 def py_encode_basestring_ascii(s, _PY3=PY3):
66  """Return an ASCII-only JSON representation of a Python string
67 
68  """
69  if _PY3:
70  if isinstance(s, bytes):
71  s = str(s, 'utf-8')
72  elif type(s) is not str:
73  # convert an str subclass instance to exact str
74  # raise a TypeError otherwise
75  s = str.__str__(s)
76  else:
77  if isinstance(s, str) and HAS_UTF8.search(s) is not None:
78  s = unicode(s, 'utf-8')
79  elif type(s) not in (str, unicode):
80  # convert an str subclass instance to exact str
81  # convert a unicode subclass instance to exact unicode
82  # raise a TypeError otherwise
83  if isinstance(s, str):
84  s = str.__str__(s)
85  else:
86  s = unicode.__getnewargs__(s)[0]
87  def replace(match):
88  s = match.group(0)
89  try:
90  return ESCAPE_DCT[s]
91  except KeyError:
92  n = ord(s)
93  if n < 0x10000:
94  #return '\\u{0:04x}'.format(n)
95  return '\\u%04x' % (n,)
96  else:
97  # surrogate pair
98  n -= 0x10000
99  s1 = 0xd800 | ((n >> 10) & 0x3ff)
100  s2 = 0xdc00 | (n & 0x3ff)
101  #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
102  return '\\u%04x\\u%04x' % (s1, s2)
103  return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
104 
105 
106 encode_basestring_ascii = (
107  c_encode_basestring_ascii or py_encode_basestring_ascii)
108 
109 class JSONEncoder(object):
110  """Extensible JSON <http://json.org> encoder for Python data structures.
111 
112  Supports the following objects and types by default:
113 
114  +-------------------+---------------+
115  | Python | JSON |
116  +===================+===============+
117  | dict, namedtuple | object |
118  +-------------------+---------------+
119  | list, tuple | array |
120  +-------------------+---------------+
121  | str, unicode | string |
122  +-------------------+---------------+
123  | int, long, float | number |
124  +-------------------+---------------+
125  | True | true |
126  +-------------------+---------------+
127  | False | false |
128  +-------------------+---------------+
129  | None | null |
130  +-------------------+---------------+
131 
132  To extend this to recognize other objects, subclass and implement a
133  ``.default()`` method with another method that returns a serializable
134  object for ``o`` if possible, otherwise it should call the superclass
135  implementation (to raise ``TypeError``).
136 
137  """
138  item_separator = ', '
139  key_separator = ': '
140 
141  def __init__(self, skipkeys=False, ensure_ascii=True,
142  check_circular=True, allow_nan=True, sort_keys=False,
143  indent=None, separators=None, encoding='utf-8', default=None,
144  use_decimal=True, namedtuple_as_object=True,
145  tuple_as_array=True, bigint_as_string=False,
146  item_sort_key=None, for_json=False, ignore_nan=False,
147  int_as_string_bitcount=None, iterable_as_array=False):
148  """Constructor for JSONEncoder, with sensible defaults.
149 
150  If skipkeys is false, then it is a TypeError to attempt
151  encoding of keys that are not str, int, long, float or None. If
152  skipkeys is True, such items are simply skipped.
153 
154  If ensure_ascii is true, the output is guaranteed to be str
155  objects with all incoming unicode characters escaped. If
156  ensure_ascii is false, the output will be unicode object.
157 
158  If check_circular is true, then lists, dicts, and custom encoded
159  objects will be checked for circular references during encoding to
160  prevent an infinite recursion (which would cause an OverflowError).
161  Otherwise, no such check takes place.
162 
163  If allow_nan is true, then NaN, Infinity, and -Infinity will be
164  encoded as such. This behavior is not JSON specification compliant,
165  but is consistent with most JavaScript based encoders and decoders.
166  Otherwise, it will be a ValueError to encode such floats.
167 
168  If sort_keys is true, then the output of dictionaries will be
169  sorted by key; this is useful for regression tests to ensure
170  that JSON serializations can be compared on a day-to-day basis.
171 
172  If indent is a string, then JSON array elements and object members
173  will be pretty-printed with a newline followed by that string repeated
174  for each level of nesting. ``None`` (the default) selects the most compact
175  representation without any newlines. For backwards compatibility with
176  versions of simplejson earlier than 2.1.0, an integer is also accepted
177  and is converted to a string with that many spaces.
178 
179  If specified, separators should be an (item_separator, key_separator)
180  tuple. The default is (', ', ': ') if *indent* is ``None`` and
181  (',', ': ') otherwise. To get the most compact JSON representation,
182  you should specify (',', ':') to eliminate whitespace.
183 
184  If specified, default is a function that gets called for objects
185  that can't otherwise be serialized. It should return a JSON encodable
186  version of the object or raise a ``TypeError``.
187 
188  If encoding is not None, then all input strings will be
189  transformed into unicode using that encoding prior to JSON-encoding.
190  The default is UTF-8.
191 
192  If use_decimal is true (default: ``True``), ``decimal.Decimal`` will
193  be supported directly by the encoder. For the inverse, decode JSON
194  with ``parse_float=decimal.Decimal``.
195 
196  If namedtuple_as_object is true (the default), objects with
197  ``_asdict()`` methods will be encoded as JSON objects.
198 
199  If tuple_as_array is true (the default), tuple (and subclasses) will
200  be encoded as JSON arrays.
201 
202  If *iterable_as_array* is true (default: ``False``),
203  any object not in the above table that implements ``__iter__()``
204  will be encoded as a JSON array.
205 
206  If bigint_as_string is true (not the default), ints 2**53 and higher
207  or lower than -2**53 will be encoded as strings. This is to avoid the
208  rounding that happens in Javascript otherwise.
209 
210  If int_as_string_bitcount is a positive number (n), then int of size
211  greater than or equal to 2**n or lower than or equal to -2**n will be
212  encoded as strings.
213 
214  If specified, item_sort_key is a callable used to sort the items in
215  each dictionary. This is useful if you want to sort items other than
216  in alphabetical order by key.
217 
218  If for_json is true (not the default), objects with a ``for_json()``
219  method will use the return value of that method for encoding as JSON
220  instead of the object.
221 
222  If *ignore_nan* is true (default: ``False``), then out of range
223  :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized
224  as ``null`` in compliance with the ECMA-262 specification. If true,
225  this will override *allow_nan*.
226 
227  """
228 
229  self.skipkeys = skipkeys
230  self.ensure_ascii = ensure_ascii
231  self.check_circular = check_circular
232  self.allow_nan = allow_nan
233  self.sort_keys = sort_keys
234  self.use_decimal = use_decimal
235  self.namedtuple_as_object = namedtuple_as_object
236  self.tuple_as_array = tuple_as_array
237  self.iterable_as_array = iterable_as_array
238  self.bigint_as_string = bigint_as_string
239  self.item_sort_key = item_sort_key
240  self.for_json = for_json
241  self.ignore_nan = ignore_nan
242  self.int_as_string_bitcount = int_as_string_bitcount
243  if indent is not None and not isinstance(indent, string_types):
244  indent = indent * ' '
245  self.indent = indent
246  if separators is not None:
247  self.item_separator, self.key_separator = separators
248  elif indent is not None:
249  self.item_separator = ','
250  if default is not None:
251  self.default = default
252  self.encoding = encoding
253 
254  def default(self, o):
255  """Implement this method in a subclass such that it returns
256  a serializable object for ``o``, or calls the base implementation
257  (to raise a ``TypeError``).
258 
259  For example, to support arbitrary iterators, you could
260  implement default like this::
261 
262  def default(self, o):
263  try:
264  iterable = iter(o)
265  except TypeError:
266  pass
267  else:
268  return list(iterable)
269  return JSONEncoder.default(self, o)
270 
271  """
272  raise TypeError('Object of type %s is not JSON serializable' %
273  o.__class__.__name__)
274 
275  def encode(self, o):
276  """Return a JSON string representation of a Python data structure.
277 
278  >>> from simplejson import JSONEncoder
279  >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
280  '{"foo": ["bar", "baz"]}'
281 
282  """
283  # This is for extremely simple cases and benchmarks.
284  if isinstance(o, binary_type):
285  _encoding = self.encoding
286  if (_encoding is not None and not (_encoding == 'utf-8')):
287  o = text_type(o, _encoding)
288  if isinstance(o, string_types):
289  if self.ensure_ascii:
290  return encode_basestring_ascii(o)
291  else:
292  return encode_basestring(o)
293  # This doesn't pass the iterator directly to ''.join() because the
294  # exceptions aren't as detailed. The list call should be roughly
295  # equivalent to the PySequence_Fast that ''.join() would do.
296  chunks = self.iterencode(o, _one_shot=True)
297  if not isinstance(chunks, (list, tuple)):
298  chunks = list(chunks)
299  if self.ensure_ascii:
300  return ''.join(chunks)
301  else:
302  return u''.join(chunks)
303 
304  def iterencode(self, o, _one_shot=False):
305  """Encode the given object and yield each string
306  representation as available.
307 
308  For example::
309 
310  for chunk in JSONEncoder().iterencode(bigobject):
311  mysocket.write(chunk)
312 
313  """
314  if self.check_circular:
315  markers = {}
316  else:
317  markers = None
318  if self.ensure_ascii:
319  _encoder = encode_basestring_ascii
320  else:
321  _encoder = encode_basestring
322  if self.encoding != 'utf-8' and self.encoding is not None:
323  def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
324  if isinstance(o, binary_type):
325  o = text_type(o, _encoding)
326  return _orig_encoder(o)
327 
328  def floatstr(o, allow_nan=self.allow_nan, ignore_nan=self.ignore_nan,
329  _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf):
330  # Check for specials. Note that this type of test is processor
331  # and/or platform-specific, so do tests which don't depend on
332  # the internals.
333 
334  if o != o:
335  text = 'NaN'
336  elif o == _inf:
337  text = 'Infinity'
338  elif o == _neginf:
339  text = '-Infinity'
340  else:
341  if type(o) != float:
342  # See #118, do not trust custom str/repr
343  o = float(o)
344  return _repr(o)
345 
346  if ignore_nan:
347  text = 'null'
348  elif not allow_nan:
349  raise ValueError(
350  "Out of range float values are not JSON compliant: " +
351  repr(o))
352 
353  return text
354 
355  key_memo = {}
356  int_as_string_bitcount = (
357  53 if self.bigint_as_string else self.int_as_string_bitcount)
358  if (_one_shot and c_make_encoder is not None
359  and self.indent is None):
360  _iterencode = c_make_encoder(
361  markers, self.default, _encoder, self.indent,
362  self.key_separator, self.item_separator, self.sort_keys,
363  self.skipkeys, self.allow_nan, key_memo, self.use_decimal,
365  int_as_string_bitcount,
366  self.item_sort_key, self.encoding, self.for_json,
367  self.ignore_nan, decimal.Decimal, self.iterable_as_array)
368  else:
369  _iterencode = _make_iterencode(
370  markers, self.default, _encoder, self.indent, floatstr,
371  self.key_separator, self.item_separator, self.sort_keys,
372  self.skipkeys, _one_shot, self.use_decimal,
374  int_as_string_bitcount,
375  self.item_sort_key, self.encoding, self.for_json,
376  self.iterable_as_array, Decimal=decimal.Decimal)
377  try:
378  return _iterencode(o, 0)
379  finally:
380  key_memo.clear()
381 
382 
384  """An encoder that produces JSON safe to embed in HTML.
385 
386  To embed JSON content in, say, a script tag on a web page, the
387  characters &, < and > should be escaped. They cannot be escaped
388  with the usual entities (e.g. &amp;) because they are not expanded
389  within <script> tags.
390 
391  This class also escapes the line separator and paragraph separator
392  characters U+2028 and U+2029, irrespective of the ensure_ascii setting,
393  as these characters are not valid in JavaScript strings (see
394  http://timelessrepo.com/json-isnt-a-javascript-subset).
395  """
396 
397  def encode(self, o):
398  # Override JSONEncoder.encode because it has hacks for
399  # performance that make things more complicated.
400  chunks = self.iterencode(o, True)
401  if self.ensure_ascii:
402  return ''.join(chunks)
403  else:
404  return u''.join(chunks)
405 
406  def iterencode(self, o, _one_shot=False):
407  chunks = super(JSONEncoderForHTML, self).iterencode(o, _one_shot)
408  for chunk in chunks:
409  chunk = chunk.replace('&', '\\u0026')
410  chunk = chunk.replace('<', '\\u003c')
411  chunk = chunk.replace('>', '\\u003e')
412 
413  if not self.ensure_ascii:
414  chunk = chunk.replace(u'\u2028', '\\u2028')
415  chunk = chunk.replace(u'\u2029', '\\u2029')
416 
417  yield chunk
418 
419 
420 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
421  _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
422  _use_decimal, _namedtuple_as_object, _tuple_as_array,
423  _int_as_string_bitcount, _item_sort_key,
424  _encoding,_for_json,
425  _iterable_as_array,
426 
427  _PY3=PY3,
428  ValueError=ValueError,
429  string_types=string_types,
430  Decimal=None,
431  dict=dict,
432  float=float,
433  id=id,
434  integer_types=integer_types,
435  isinstance=isinstance,
436  list=list,
437  str=str,
438  tuple=tuple,
439  iter=iter,
440  ):
441  if _use_decimal and Decimal is None:
442  Decimal = decimal.Decimal
443  if _item_sort_key and not callable(_item_sort_key):
444  raise TypeError("item_sort_key must be None or callable")
445  elif _sort_keys and not _item_sort_key:
446  _item_sort_key = itemgetter(0)
447 
448  if (_int_as_string_bitcount is not None and
449  (_int_as_string_bitcount <= 0 or
450  not isinstance(_int_as_string_bitcount, integer_types))):
451  raise TypeError("int_as_string_bitcount must be a positive integer")
452 
453  def _encode_int(value):
454  skip_quoting = (
455  _int_as_string_bitcount is None
456  or
457  _int_as_string_bitcount < 1
458  )
459  if type(value) not in integer_types:
460  # See #118, do not trust custom str/repr
461  value = int(value)
462  if (
463  skip_quoting or
464  (-1 << _int_as_string_bitcount)
465  < value <
466  (1 << _int_as_string_bitcount)
467  ):
468  return str(value)
469  return '"' + str(value) + '"'
470 
471  def _iterencode_list(lst, _current_indent_level):
472  if not lst:
473  yield '[]'
474  return
475  if markers is not None:
476  markerid = id(lst)
477  if markerid in markers:
478  raise ValueError("Circular reference detected")
479  markers[markerid] = lst
480  buf = '['
481  if _indent is not None:
482  _current_indent_level += 1
483  newline_indent = '\n' + (_indent * _current_indent_level)
484  separator = _item_separator + newline_indent
485  buf += newline_indent
486  else:
487  newline_indent = None
488  separator = _item_separator
489  first = True
490  for value in lst:
491  if first:
492  first = False
493  else:
494  buf = separator
495  if isinstance(value, string_types):
496  yield buf + _encoder(value)
497  elif _PY3 and isinstance(value, bytes) and _encoding is not None:
498  yield buf + _encoder(value)
499  elif isinstance(value, RawJSON):
500  yield buf + value.encoded_json
501  elif value is None:
502  yield buf + 'null'
503  elif value is True:
504  yield buf + 'true'
505  elif value is False:
506  yield buf + 'false'
507  elif isinstance(value, integer_types):
508  yield buf + _encode_int(value)
509  elif isinstance(value, float):
510  yield buf + _floatstr(value)
511  elif _use_decimal and isinstance(value, Decimal):
512  yield buf + str(value)
513  else:
514  yield buf
515  for_json = _for_json and getattr(value, 'for_json', None)
516  if for_json and callable(for_json):
517  chunks = _iterencode(for_json(), _current_indent_level)
518  elif isinstance(value, list):
519  chunks = _iterencode_list(value, _current_indent_level)
520  else:
521  _asdict = _namedtuple_as_object and getattr(value, '_asdict', None)
522  if _asdict and callable(_asdict):
523  chunks = _iterencode_dict(_asdict(),
524  _current_indent_level)
525  elif _tuple_as_array and isinstance(value, tuple):
526  chunks = _iterencode_list(value, _current_indent_level)
527  elif isinstance(value, dict):
528  chunks = _iterencode_dict(value, _current_indent_level)
529  else:
530  chunks = _iterencode(value, _current_indent_level)
531  for chunk in chunks:
532  yield chunk
533  if first:
534  # iterable_as_array misses the fast path at the top
535  yield '[]'
536  else:
537  if newline_indent is not None:
538  _current_indent_level -= 1
539  yield '\n' + (_indent * _current_indent_level)
540  yield ']'
541  if markers is not None:
542  del markers[markerid]
543 
544  def _stringify_key(key):
545  if isinstance(key, string_types): # pragma: no cover
546  pass
547  elif _PY3 and isinstance(key, bytes) and _encoding is not None:
548  key = str(key, _encoding)
549  elif isinstance(key, float):
550  key = _floatstr(key)
551  elif key is True:
552  key = 'true'
553  elif key is False:
554  key = 'false'
555  elif key is None:
556  key = 'null'
557  elif isinstance(key, integer_types):
558  if type(key) not in integer_types:
559  # See #118, do not trust custom str/repr
560  key = int(key)
561  key = str(key)
562  elif _use_decimal and isinstance(key, Decimal):
563  key = str(key)
564  elif _skipkeys:
565  key = None
566  else:
567  raise TypeError('keys must be str, int, float, bool or None, '
568  'not %s' % key.__class__.__name__)
569  return key
570 
571  def _iterencode_dict(dct, _current_indent_level):
572  if not dct:
573  yield '{}'
574  return
575  if markers is not None:
576  markerid = id(dct)
577  if markerid in markers:
578  raise ValueError("Circular reference detected")
579  markers[markerid] = dct
580  yield '{'
581  if _indent is not None:
582  _current_indent_level += 1
583  newline_indent = '\n' + (_indent * _current_indent_level)
584  item_separator = _item_separator + newline_indent
585  yield newline_indent
586  else:
587  newline_indent = None
588  item_separator = _item_separator
589  first = True
590  if _PY3:
591  iteritems = dct.items()
592  else:
593  iteritems = dct.iteritems()
594  if _item_sort_key:
595  items = []
596  for k, v in dct.items():
597  if not isinstance(k, string_types):
598  k = _stringify_key(k)
599  if k is None:
600  continue
601  items.append((k, v))
602  items.sort(key=_item_sort_key)
603  else:
604  items = iteritems
605  for key, value in items:
606  if not (_item_sort_key or isinstance(key, string_types)):
607  key = _stringify_key(key)
608  if key is None:
609  # _skipkeys must be True
610  continue
611  if first:
612  first = False
613  else:
614  yield item_separator
615  yield _encoder(key)
616  yield _key_separator
617  if isinstance(value, string_types):
618  yield _encoder(value)
619  elif _PY3 and isinstance(value, bytes) and _encoding is not None:
620  yield _encoder(value)
621  elif isinstance(value, RawJSON):
622  yield value.encoded_json
623  elif value is None:
624  yield 'null'
625  elif value is True:
626  yield 'true'
627  elif value is False:
628  yield 'false'
629  elif isinstance(value, integer_types):
630  yield _encode_int(value)
631  elif isinstance(value, float):
632  yield _floatstr(value)
633  elif _use_decimal and isinstance(value, Decimal):
634  yield str(value)
635  else:
636  for_json = _for_json and getattr(value, 'for_json', None)
637  if for_json and callable(for_json):
638  chunks = _iterencode(for_json(), _current_indent_level)
639  elif isinstance(value, list):
640  chunks = _iterencode_list(value, _current_indent_level)
641  else:
642  _asdict = _namedtuple_as_object and getattr(value, '_asdict', None)
643  if _asdict and callable(_asdict):
644  chunks = _iterencode_dict(_asdict(),
645  _current_indent_level)
646  elif _tuple_as_array and isinstance(value, tuple):
647  chunks = _iterencode_list(value, _current_indent_level)
648  elif isinstance(value, dict):
649  chunks = _iterencode_dict(value, _current_indent_level)
650  else:
651  chunks = _iterencode(value, _current_indent_level)
652  for chunk in chunks:
653  yield chunk
654  if newline_indent is not None:
655  _current_indent_level -= 1
656  yield '\n' + (_indent * _current_indent_level)
657  yield '}'
658  if markers is not None:
659  del markers[markerid]
660 
661  def _iterencode(o, _current_indent_level):
662  if isinstance(o, string_types):
663  yield _encoder(o)
664  elif _PY3 and isinstance(o, bytes) and _encoding is not None:
665  yield _encoder(o)
666  elif isinstance(o, RawJSON):
667  yield o.encoded_json
668  elif o is None:
669  yield 'null'
670  elif o is True:
671  yield 'true'
672  elif o is False:
673  yield 'false'
674  elif isinstance(o, integer_types):
675  yield _encode_int(o)
676  elif isinstance(o, float):
677  yield _floatstr(o)
678  else:
679  for_json = _for_json and getattr(o, 'for_json', None)
680  if for_json and callable(for_json):
681  for chunk in _iterencode(for_json(), _current_indent_level):
682  yield chunk
683  elif isinstance(o, list):
684  for chunk in _iterencode_list(o, _current_indent_level):
685  yield chunk
686  else:
687  _asdict = _namedtuple_as_object and getattr(o, '_asdict', None)
688  if _asdict and callable(_asdict):
689  for chunk in _iterencode_dict(_asdict(),
690  _current_indent_level):
691  yield chunk
692  elif (_tuple_as_array and isinstance(o, tuple)):
693  for chunk in _iterencode_list(o, _current_indent_level):
694  yield chunk
695  elif isinstance(o, dict):
696  for chunk in _iterencode_dict(o, _current_indent_level):
697  yield chunk
698  elif _use_decimal and isinstance(o, Decimal):
699  yield str(o)
700  else:
701  while _iterable_as_array:
702  # Markers are not checked here because it is valid for
703  # an iterable to return self.
704  try:
705  o = iter(o)
706  except TypeError:
707  break
708  for chunk in _iterencode_list(o, _current_indent_level):
709  yield chunk
710  return
711  if markers is not None:
712  markerid = id(o)
713  if markerid in markers:
714  raise ValueError("Circular reference detected")
715  markers[markerid] = o
716  o = _default(o)
717  for chunk in _iterencode(o, _current_indent_level):
718  yield chunk
719  if markers is not None:
720  del markers[markerid]
721 
722  return _iterencode
aestate.ajson.sim.encoder.JSONEncoder.check_circular
check_circular
Definition: encoder.py:225
aestate.ajson.sim.encoder.JSONEncoder.encode
def encode(self, o)
Definition: encoder.py:275
aestate.ajson.sim.encoder.JSONEncoder.for_json
for_json
Definition: encoder.py:234
aestate.ajson.sim.encoder.JSONEncoder.namedtuple_as_object
namedtuple_as_object
Definition: encoder.py:229
aestate.ajson.sim.encoder.JSONEncoder.use_decimal
use_decimal
Definition: encoder.py:228
aestate.ajson.sim.encoder.JSONEncoder.__init__
def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)
Definition: encoder.py:141
aestate.ajson.sim.encoder.JSONEncoder.iterable_as_array
iterable_as_array
Definition: encoder.py:231
aestate.ajson.sim.encoder.JSONEncoder.item_separator
string item_separator
Definition: encoder.py:138
aestate.ajson.sim.encoder.JSONEncoderForHTML.encode
def encode(self, o)
Definition: encoder.py:397
aestate.ajson.sim.encoder.JSONEncoder.int_as_string_bitcount
int_as_string_bitcount
Definition: encoder.py:236
aestate.ajson.sim.encoder.JSONEncoder.indent
indent
Definition: encoder.py:239
aestate.ajson.sim.encoder.JSONEncoder.ignore_nan
ignore_nan
Definition: encoder.py:235
aestate.ajson.sim.encoder.JSONEncoder.encoding
encoding
Definition: encoder.py:246
aestate.ajson.sim.encoder._import_speedups
def _import_speedups()
Definition: encoder.py:9
aestate.ajson.sim.encoder.JSONEncoderForHTML
Definition: encoder.py:383
aestate.ajson.sim.encoder.JSONEncoder.default
default
Definition: encoder.py:245
aestate.ajson.sim.encoder.py_encode_basestring_ascii
def py_encode_basestring_ascii(s, _PY3=PY3)
Definition: encoder.py:65
aestate.ajson.sim.encoder.JSONEncoder.ensure_ascii
ensure_ascii
Definition: encoder.py:224
aestate.ajson.sim.encoder.encode_basestring_ascii
tuple encode_basestring_ascii
Definition: encoder.py:106
aestate.ajson.sim.encoder.JSONEncoder.tuple_as_array
tuple_as_array
Definition: encoder.py:230
aestate.ajson.sim.encoder._make_iterencode
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, _use_decimal, _namedtuple_as_object, _tuple_as_array, _int_as_string_bitcount, _item_sort_key, _encoding, _for_json, _iterable_as_array, _PY3=PY3, ValueError=ValueError, string_types=string_types, Decimal=None, dict=dict, float=float, id=id, integer_types=integer_types, isinstance=isinstance, list=list, str=str, tuple=tuple, iter=iter)
Definition: encoder.py:420
aestate.ajson.sim.encoder.JSONEncoderForHTML.iterencode
def iterencode(self, o, _one_shot=False)
Definition: encoder.py:406
aestate.ajson.sim.encoder.JSONEncoder.item_sort_key
item_sort_key
Definition: encoder.py:233
aestate.ajson.sim.encoder.JSONEncoder.iterencode
def iterencode(self, o, _one_shot=False)
Definition: encoder.py:304
aestate.ajson.sim.encoder.JSONEncoder.bigint_as_string
bigint_as_string
Definition: encoder.py:232
aestate.ajson.sim.compat.text_type
text_type
Definition: compat.py:18
aestate.ajson.sim.encoder.JSONEncoder.allow_nan
allow_nan
Definition: encoder.py:226
aestate.ajson.sim.encoder.JSONEncoder.skipkeys
skipkeys
Definition: encoder.py:223
aestate.ajson.sim.encoder.JSONEncoder.key_separator
string key_separator
Definition: encoder.py:139
aestate.ajson.sim.encoder.encode_basestring
def encode_basestring(s, _PY3=PY3, _q=u'"')
Definition: encoder.py:38
aestate.ajson.sim.encoder.JSONEncoder.sort_keys
sort_keys
Definition: encoder.py:227
aestate.ajson.sim.encoder.JSONEncoder
Definition: encoder.py:109