encoder.py 27 KB

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