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.

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