PageRenderTime 55ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/extensions/SemanticResultFormats/Exhibit/exhibit/extensions/curate/files/admin/simplejson/encoder.py

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