encoder.py 16 KB

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