/dryapp/simplejson/encoder.py

http://github.com/darwin/drydrop · Python · 433 lines · 302 code · 28 blank · 103 comment · 102 complexity · 00986723864831ae6064761aadd48239 MD5 · raw file

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