encoder.py 28 KB

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