You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

440 lines
16 KiB

16 years ago
  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. FLOAT_REPR = repr
  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 <http://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 OverflowError).
  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 JSONEncoder.default(self, o)
  148. """
  149. raise TypeError(repr(o) + " 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. ):
  227. if _indent is not None and not isinstance(_indent, str):
  228. _indent = ' ' * _indent
  229. def _iterencode_list(lst, _current_indent_level):
  230. if not lst:
  231. yield '[]'
  232. return
  233. if markers is not None:
  234. markerid = id(lst)
  235. if markerid in markers:
  236. raise ValueError("Circular reference detected")
  237. markers[markerid] = lst
  238. buf = '['
  239. if _indent is not None:
  240. _current_indent_level += 1
  241. newline_indent = '\n' + _indent * _current_indent_level
  242. separator = _item_separator + newline_indent
  243. buf += newline_indent
  244. else:
  245. newline_indent = None
  246. separator = _item_separator
  247. first = True
  248. for value in lst:
  249. if first:
  250. first = False
  251. else:
  252. buf = separator
  253. if isinstance(value, str):
  254. yield buf + _encoder(value)
  255. elif value is None:
  256. yield buf + 'null'
  257. elif value is True:
  258. yield buf + 'true'
  259. elif value is False:
  260. yield buf + 'false'
  261. elif isinstance(value, int):
  262. # Subclasses of int/float may override __str__, but we still
  263. # want to encode them as integers/floats in JSON. One example
  264. # within the standard library is IntEnum.
  265. yield buf + str(int(value))
  266. elif isinstance(value, float):
  267. # see comment above for int
  268. yield buf + _floatstr(float(value))
  269. else:
  270. yield buf
  271. if isinstance(value, (list, tuple)):
  272. chunks = _iterencode_list(value, _current_indent_level)
  273. elif isinstance(value, dict):
  274. chunks = _iterencode_dict(value, _current_indent_level)
  275. else:
  276. chunks = _iterencode(value, _current_indent_level)
  277. yield from chunks
  278. if newline_indent is not None:
  279. _current_indent_level -= 1
  280. yield '\n' + _indent * _current_indent_level
  281. yield ']'
  282. if markers is not None:
  283. del markers[markerid]
  284. def _iterencode_dict(dct, _current_indent_level):
  285. if not dct:
  286. yield '{}'
  287. return
  288. if markers is not None:
  289. markerid = id(dct)
  290. if markerid in markers:
  291. raise ValueError("Circular reference detected")
  292. markers[markerid] = dct
  293. yield '{'
  294. if _indent is not None:
  295. _current_indent_level += 1
  296. newline_indent = '\n' + _indent * _current_indent_level
  297. item_separator = _item_separator + newline_indent
  298. yield newline_indent
  299. else:
  300. newline_indent = None
  301. item_separator = _item_separator
  302. first = True
  303. if _sort_keys:
  304. items = sorted(dct.items(), key=lambda kv: kv[0])
  305. else:
  306. items = dct.items()
  307. for key, value in items:
  308. if isinstance(key, str):
  309. pass
  310. # JavaScript is weakly typed for these, so it makes sense to
  311. # also allow them. Many encoders seem to do something like this.
  312. elif isinstance(key, float):
  313. # see comment for int/float in _make_iterencode
  314. key = _floatstr(float(key))
  315. elif key is True:
  316. key = 'true'
  317. elif key is False:
  318. key = 'false'
  319. elif key is None:
  320. key = 'null'
  321. elif isinstance(key, int):
  322. # see comment for int/float in _make_iterencode
  323. key = str(int(key))
  324. elif _skipkeys:
  325. continue
  326. else:
  327. raise TypeError("key " + repr(key) + " is not a string")
  328. if first:
  329. first = False
  330. else:
  331. yield item_separator
  332. yield _encoder(key)
  333. yield _key_separator
  334. if isinstance(value, str):
  335. yield _encoder(value)
  336. elif value is None:
  337. yield 'null'
  338. elif value is True:
  339. yield 'true'
  340. elif value is False:
  341. yield 'false'
  342. elif isinstance(value, int):
  343. # see comment for int/float in _make_iterencode
  344. yield str(int(value))
  345. elif isinstance(value, float):
  346. # see comment for int/float in _make_iterencode
  347. yield _floatstr(float(value))
  348. else:
  349. if isinstance(value, (list, tuple)):
  350. chunks = _iterencode_list(value, _current_indent_level)
  351. elif isinstance(value, dict):
  352. chunks = _iterencode_dict(value, _current_indent_level)
  353. else:
  354. chunks = _iterencode(value, _current_indent_level)
  355. yield from chunks
  356. if newline_indent is not None:
  357. _current_indent_level -= 1
  358. yield '\n' + _indent * _current_indent_level
  359. yield '}'
  360. if markers is not None:
  361. del markers[markerid]
  362. def _iterencode(o, _current_indent_level):
  363. if isinstance(o, str):
  364. yield _encoder(o)
  365. elif o is None:
  366. yield 'null'
  367. elif o is True:
  368. yield 'true'
  369. elif o is False:
  370. yield 'false'
  371. elif isinstance(o, int):
  372. # see comment for int/float in _make_iterencode
  373. yield str(int(o))
  374. elif isinstance(o, float):
  375. # see comment for int/float in _make_iterencode
  376. yield _floatstr(float(o))
  377. elif isinstance(o, (list, tuple)):
  378. yield from _iterencode_list(o, _current_indent_level)
  379. elif isinstance(o, dict):
  380. yield from _iterencode_dict(o, _current_indent_level)
  381. else:
  382. if markers is not None:
  383. markerid = id(o)
  384. if markerid in markers:
  385. raise ValueError("Circular reference detected")
  386. markers[markerid] = o
  387. o = _default(o)
  388. yield from _iterencode(o, _current_indent_level)
  389. if markers is not None:
  390. del markers[markerid]
  391. return _iterencode