encoder.py 16 KB

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