encoder.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. """Implementation of JSONEncoder
  2. """
  3. import re
  4. try:
  5. from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
  6. except ImportError:
  7. c_encode_basestring_ascii = None
  8. try:
  9. from simplejson._speedups 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(r'[\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. if isinstance(s, str) and HAS_UTF8.search(s) is not None:
  40. s = s.decode('utf-8')
  41. def replace(match):
  42. s = match.group(0)
  43. try:
  44. return ESCAPE_DCT[s]
  45. except KeyError:
  46. n = ord(s)
  47. if n < 0x10000:
  48. #return '\\u{0:04x}'.format(n)
  49. return '\\u%04x' % (n,)
  50. else:
  51. # surrogate pair
  52. n -= 0x10000
  53. s1 = 0xd800 | ((n >> 10) & 0x3ff)
  54. s2 = 0xdc00 | (n & 0x3ff)
  55. #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
  56. return '\\u%04x\\u%04x' % (s1, s2)
  57. return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
  58. encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
  59. class JSONEncoder(object):
  60. """Extensible JSON <http://json.org> encoder for Python data structures.
  61. Supports the following objects and types by default:
  62. +-------------------+---------------+
  63. | Python | JSON |
  64. +===================+===============+
  65. | dict | object |
  66. +-------------------+---------------+
  67. | list, tuple | array |
  68. +-------------------+---------------+
  69. | str, unicode | string |
  70. +-------------------+---------------+
  71. | int, long, float | number |
  72. +-------------------+---------------+
  73. | True | true |
  74. +-------------------+---------------+
  75. | False | false |
  76. +-------------------+---------------+
  77. | None | null |
  78. +-------------------+---------------+
  79. To extend this to recognize other objects, subclass and implement a
  80. ``.default()`` method with another method that returns a serializable
  81. object for ``o`` if possible, otherwise it should call the superclass
  82. implementation (to raise ``TypeError``).
  83. """
  84. item_separator = ', '
  85. key_separator = ': '
  86. def __init__(self, skipkeys=False, ensure_ascii=True,
  87. check_circular=True, allow_nan=True, sort_keys=False,
  88. indent=None, separators=None, encoding='utf-8', default=None):
  89. """Constructor for JSONEncoder, with sensible defaults.
  90. If skipkeys is false, then it is a TypeError to attempt
  91. encoding of keys that are not str, int, long, float or None. If
  92. skipkeys is True, such items are simply skipped.
  93. If ensure_ascii is true, the output is guaranteed to be str
  94. objects with all incoming unicode characters escaped. If
  95. ensure_ascii is false, the output will be unicode object.
  96. If check_circular is true, then lists, dicts, and custom encoded
  97. objects will be checked for circular references during encoding to
  98. prevent an infinite recursion (which would cause an OverflowError).
  99. Otherwise, no such check takes place.
  100. If allow_nan is true, then NaN, Infinity, and -Infinity will be
  101. encoded as such. This behavior is not JSON specification compliant,
  102. but is consistent with most JavaScript based encoders and decoders.
  103. Otherwise, it will be a ValueError to encode such floats.
  104. If sort_keys is true, then the output of dictionaries will be
  105. sorted by key; this is useful for regression tests to ensure
  106. that JSON serializations can be compared on a day-to-day basis.
  107. If indent is a non-negative integer, then JSON array
  108. elements and object members will be pretty-printed with that
  109. indent level. An indent level of 0 will only insert newlines.
  110. None is the most compact representation.
  111. If specified, separators should be a (item_separator, key_separator)
  112. tuple. The default is (', ', ': '). To get the most compact JSON
  113. representation you should specify (',', ':') to eliminate whitespace.
  114. If specified, default is a function that gets called for objects
  115. that can't otherwise be serialized. It should return a JSON encodable
  116. version of the object or raise a ``TypeError``.
  117. If encoding is not None, then all input strings will be
  118. transformed into unicode using that encoding prior to JSON-encoding.
  119. The default is UTF-8.
  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. if default is not None:
  130. self.default = default
  131. self.encoding = encoding
  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. return JSONEncoder.default(self, o)
  146. """
  147. raise TypeError(repr(o) + " is not JSON serializable")
  148. def encode(self, o):
  149. """Return a JSON string representation of a Python data structure.
  150. >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  151. '{"foo": ["bar", "baz"]}'
  152. """
  153. # This is for extremely simple cases and benchmarks.
  154. if isinstance(o, basestring):
  155. if isinstance(o, str):
  156. _encoding = self.encoding
  157. if (_encoding is not None
  158. and not (_encoding == 'utf-8')):
  159. o = o.decode(_encoding)
  160. if self.ensure_ascii:
  161. return encode_basestring_ascii(o)
  162. else:
  163. return encode_basestring(o)
  164. # This doesn't pass the iterator directly to ''.join() because the
  165. # exceptions aren't as detailed. The list call should be roughly
  166. # equivalent to the PySequence_Fast that ''.join() would do.
  167. chunks = self.iterencode(o, _one_shot=True)
  168. if not isinstance(chunks, (list, tuple)):
  169. chunks = list(chunks)
  170. return ''.join(chunks)
  171. def iterencode(self, o, _one_shot=False):
  172. """Encode the given object and yield each string
  173. representation as available.
  174. For example::
  175. for chunk in JSONEncoder().iterencode(bigobject):
  176. mysocket.write(chunk)
  177. """
  178. if self.check_circular:
  179. markers = {}
  180. else:
  181. markers = None
  182. if self.ensure_ascii:
  183. _encoder = encode_basestring_ascii
  184. else:
  185. _encoder = encode_basestring
  186. if self.encoding != 'utf-8':
  187. def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
  188. if isinstance(o, str):
  189. o = o.decode(_encoding)
  190. return _orig_encoder(o)
  191. def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
  192. # Check for specials. Note that this type of test is processor- and/or
  193. # platform-specific, so do tests which don't depend on the internals.
  194. if o != o:
  195. text = 'NaN'
  196. elif o == _inf:
  197. text = 'Infinity'
  198. elif o == _neginf:
  199. text = '-Infinity'
  200. else:
  201. return _repr(o)
  202. if not allow_nan:
  203. raise ValueError(
  204. "Out of range float values are not JSON compliant: " +
  205. repr(o))
  206. return text
  207. if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
  208. _iterencode = c_make_encoder(
  209. markers, self.default, _encoder, self.indent,
  210. self.key_separator, self.item_separator, self.sort_keys,
  211. self.skipkeys, self.allow_nan)
  212. else:
  213. _iterencode = _make_iterencode(
  214. markers, self.default, _encoder, self.indent, floatstr,
  215. self.key_separator, self.item_separator, self.sort_keys,
  216. self.skipkeys, _one_shot)
  217. return _iterencode(o, 0)
  218. def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
  219. ## HACK: hand-optimized bytecode; turn globals into locals
  220. False=False,
  221. True=True,
  222. ValueError=ValueError,
  223. basestring=basestring,
  224. dict=dict,
  225. float=float,
  226. id=id,
  227. int=int,
  228. isinstance=isinstance,
  229. list=list,
  230. long=long,
  231. str=str,
  232. tuple=tuple,
  233. ):
  234. def _iterencode_list(lst, _current_indent_level):
  235. if not lst:
  236. yield '[]'
  237. return
  238. if markers is not None:
  239. markerid = id(lst)
  240. if markerid in markers:
  241. raise ValueError("Circular reference detected")
  242. markers[markerid] = lst
  243. buf = '['
  244. if _indent is not None:
  245. _current_indent_level += 1
  246. newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
  247. separator = _item_separator + newline_indent
  248. buf += newline_indent
  249. else:
  250. newline_indent = None
  251. separator = _item_separator
  252. first = True
  253. for value in lst:
  254. if first:
  255. first = False
  256. else:
  257. buf = separator
  258. if isinstance(value, basestring):
  259. yield buf + _encoder(value)
  260. elif value is None:
  261. yield buf + 'null'
  262. elif value is True:
  263. yield buf + 'true'
  264. elif value is False:
  265. yield buf + 'false'
  266. elif isinstance(value, (int, long)):
  267. yield buf + str(value)
  268. elif isinstance(value, float):
  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. for chunk in chunks:
  279. yield chunk
  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 = dct.items()
  307. items.sort(key=lambda kv: kv[0])
  308. else:
  309. items = dct.iteritems()
  310. for key, value in items:
  311. if isinstance(key, basestring):
  312. pass
  313. # JavaScript is weakly typed for these, so it makes sense to
  314. # also allow them. Many encoders seem to do something like this.
  315. elif isinstance(key, float):
  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, long)):
  324. key = str(key)
  325. elif _skipkeys:
  326. continue
  327. else:
  328. raise TypeError("key " + repr(key) + " is not a string")
  329. if first:
  330. first = False
  331. else:
  332. yield item_separator
  333. yield _encoder(key)
  334. yield _key_separator
  335. if isinstance(value, basestring):
  336. yield _encoder(value)
  337. elif value is None:
  338. yield 'null'
  339. elif value is True:
  340. yield 'true'
  341. elif value is False:
  342. yield 'false'
  343. elif isinstance(value, (int, long)):
  344. yield str(value)
  345. elif isinstance(value, float):
  346. yield _floatstr(value)
  347. else:
  348. if isinstance(value, (list, tuple)):
  349. chunks = _iterencode_list(value, _current_indent_level)
  350. elif isinstance(value, dict):
  351. chunks = _iterencode_dict(value, _current_indent_level)
  352. else:
  353. chunks = _iterencode(value, _current_indent_level)
  354. for chunk in chunks:
  355. yield chunk
  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, basestring):
  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, long)):
  372. yield str(o)
  373. elif isinstance(o, float):
  374. yield _floatstr(o)
  375. elif isinstance(o, (list, tuple)):
  376. for chunk in _iterencode_list(o, _current_indent_level):
  377. yield chunk
  378. elif isinstance(o, dict):
  379. for chunk in _iterencode_dict(o, _current_indent_level):
  380. yield chunk
  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. for chunk in _iterencode(o, _current_indent_level):
  389. yield chunk
  390. if markers is not None:
  391. del markers[markerid]
  392. return _iterencode