encoder.py 13 KB

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