PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/jsonrpc/public/services/simplejson/encoder.py

http://pyjamas.googlecode.com/
Python | 307 lines | 225 code | 13 blank | 69 comment | 9 complexity | 4ac8f59b7794e6a4a5dfb13146a80107 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. """
  2. Implementation of JSONEncoder
  3. """
  4. import re
  5. ESCAPE = re.compile(r'[\x00-\x19\\"\b\f\n\r\t]')
  6. ESCAPE_ASCII = re.compile(r'([\\"/]|[^\ -~])')
  7. ESCAPE_DCT = {
  8. # escape all forward slashes to prevent </script> attack
  9. '/': '\\/',
  10. '\\': '\\\\',
  11. '"': '\\"',
  12. '\b': '\\b',
  13. '\f': '\\f',
  14. '\n': '\\n',
  15. '\r': '\\r',
  16. '\t': '\\t',
  17. }
  18. for i in range(20):
  19. ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
  20. def floatstr(o, allow_nan=True):
  21. # Check for specials. Note that this type of test is processor- and/or
  22. # platform-specific, so do tests which don't depend on the internals.
  23. # assume this produces an infinity on all machines (probably not guaranteed)
  24. INFINITY = 1e66666
  25. if o != o:
  26. text = 'NaN'
  27. elif o == INFINITY:
  28. text = 'Infinity'
  29. elif o == -INFINITY:
  30. text = '-Infinity'
  31. else:
  32. return str(o)
  33. if not allow_nan:
  34. raise ValueError("Out of range float values are not JSON compliant: %r"
  35. % (o,))
  36. return text
  37. def encode_basestring(s):
  38. """
  39. Return a JSON representation of a Python string
  40. """
  41. def replace(match):
  42. return ESCAPE_DCT[match.group(0)]
  43. return '"' + ESCAPE.sub(replace, s) + '"'
  44. def encode_basestring_ascii(s):
  45. def replace(match):
  46. s = match.group(0)
  47. try:
  48. return ESCAPE_DCT[s]
  49. except KeyError:
  50. return '\\u%04x' % (ord(s),)
  51. return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
  52. class JSONEncoder(object):
  53. """
  54. Extensible JSON <http://json.org> encoder for Python data structures.
  55. Supports the following objects and types by default:
  56. +-------------------+---------------+
  57. | Python | JSON |
  58. +===================+===============+
  59. | dict | object |
  60. +-------------------+---------------+
  61. | list, tuple | array |
  62. +-------------------+---------------+
  63. | str, unicode | string |
  64. +-------------------+---------------+
  65. | int, long, float | number |
  66. +-------------------+---------------+
  67. | True | true |
  68. +-------------------+---------------+
  69. | False | false |
  70. +-------------------+---------------+
  71. | None | null |
  72. +-------------------+---------------+
  73. To extend this to recognize other objects, subclass and implement a
  74. ``.default()`` method with another method that returns a serializable
  75. object for ``o`` if possible, otherwise it should call the superclass
  76. implementation (to raise ``TypeError``).
  77. """
  78. __all__ = ['__init__', 'default', 'encode', 'iterencode']
  79. def __init__(self, skipkeys=False, ensure_ascii=True,
  80. check_circular=True, allow_nan=True, sort_keys=False, indent=None):
  81. """
  82. Constructor for JSONEncoder, with sensible defaults.
  83. If skipkeys is False, then it is a TypeError to attempt
  84. encoding of keys that are not str, int, long, float or None. If
  85. skipkeys is True, such items are simply skipped.
  86. If ensure_ascii is True, the output is guaranteed to be str
  87. objects with all incoming unicode characters escaped. If
  88. ensure_ascii is false, the output will be unicode object.
  89. If check_circular is True, then lists, dicts, and custom encoded
  90. objects will be checked for circular references during encoding to
  91. prevent an infinite recursion (which would cause an OverflowError).
  92. Otherwise, no such check takes place.
  93. If allow_nan is True, then NaN, Infinity, and -Infinity will be
  94. encoded as such. This behavior is not JSON specification compliant,
  95. but is consistent with most JavaScript based encoders and decoders.
  96. Otherwise, it will be a ValueError to encode such floats.
  97. If sort_keys is True, then the output of dictionaries will be
  98. sorted by key; this is useful for regression tests to ensure
  99. that JSON serializations can be compared on a day-to-day basis.
  100. If ``indent`` is a non-negative integer, then JSON array
  101. elements and object members will be pretty-printed with that
  102. indent level. An indent level of 0 will only insert newlines.
  103. ``None`` is the most compact representation.
  104. """
  105. self.skipkeys = skipkeys
  106. self.ensure_ascii = ensure_ascii
  107. self.check_circular = check_circular
  108. self.allow_nan = allow_nan
  109. self.sort_keys = sort_keys
  110. self.indent = indent
  111. self.current_indent_level = 0
  112. def _newline_indent(self):
  113. if self.indent is None:
  114. return ''
  115. return '\n' + (' ' * (self.indent * self.current_indent_level))
  116. def _iterencode_list(self, lst, markers=None):
  117. if not lst:
  118. yield '[]'
  119. return
  120. if markers is not None:
  121. markerid = id(lst)
  122. if markerid in markers:
  123. raise ValueError("Circular reference detected")
  124. markers[markerid] = lst
  125. self.current_indent_level += 1
  126. newline_indent = self._newline_indent()
  127. yield '[' + newline_indent
  128. first = True
  129. for value in lst:
  130. if first:
  131. first = False
  132. else:
  133. yield ', ' + newline_indent
  134. for chunk in self._iterencode(value, markers):
  135. yield chunk
  136. self.current_indent_level -= 1
  137. yield self._newline_indent() + ']'
  138. if markers is not None:
  139. del markers[markerid]
  140. def _iterencode_dict(self, dct, markers=None):
  141. if not dct:
  142. yield '{}'
  143. return
  144. if markers is not None:
  145. markerid = id(dct)
  146. if markerid in markers:
  147. raise ValueError("Circular reference detected")
  148. markers[markerid] = dct
  149. self.current_indent_level += 1
  150. newline_indent = self._newline_indent()
  151. yield '{' + newline_indent
  152. first = True
  153. if self.ensure_ascii:
  154. encoder = encode_basestring_ascii
  155. else:
  156. encoder = encode_basestring
  157. allow_nan = self.allow_nan
  158. if self.sort_keys:
  159. keys = dct.keys()
  160. keys.sort()
  161. items = [(k,dct[k]) for k in keys]
  162. else:
  163. items = dct.iteritems()
  164. for key, value in items:
  165. if isinstance(key, basestring):
  166. pass
  167. # JavaScript is weakly typed for these, so it makes sense to
  168. # also allow them. Many encoders seem to do something like this.
  169. elif isinstance(key, float):
  170. key = floatstr(key, allow_nan)
  171. elif isinstance(key, (int, long)):
  172. key = str(key)
  173. elif key is True:
  174. key = 'true'
  175. elif key is False:
  176. key = 'false'
  177. elif key is None:
  178. key = 'null'
  179. elif self.skipkeys:
  180. continue
  181. else:
  182. raise TypeError("key %r is not a string" % (key,))
  183. if first:
  184. first = False
  185. else:
  186. yield ', ' + newline_indent
  187. yield encoder(key)
  188. yield ': '
  189. for chunk in self._iterencode(value, markers):
  190. yield chunk
  191. self.current_indent_level -= 1
  192. yield self._newline_indent() + '}'
  193. if markers is not None:
  194. del markers[markerid]
  195. def _iterencode(self, o, markers=None):
  196. if isinstance(o, basestring):
  197. if self.ensure_ascii:
  198. encoder = encode_basestring_ascii
  199. else:
  200. encoder = encode_basestring
  201. yield encoder(o)
  202. elif o is None:
  203. yield 'null'
  204. elif o is True:
  205. yield 'true'
  206. elif o is False:
  207. yield 'false'
  208. elif isinstance(o, (int, long)):
  209. yield str(o)
  210. elif isinstance(o, float):
  211. yield floatstr(o, self.allow_nan)
  212. elif isinstance(o, (list, tuple)):
  213. for chunk in self._iterencode_list(o, markers):
  214. yield chunk
  215. elif isinstance(o, dict):
  216. for chunk in self._iterencode_dict(o, markers):
  217. yield chunk
  218. else:
  219. if markers is not None:
  220. markerid = id(o)
  221. if markerid in markers:
  222. raise ValueError("Circular reference detected")
  223. markers[markerid] = o
  224. for chunk in self._iterencode_default(o, markers):
  225. yield chunk
  226. if markers is not None:
  227. del markers[markerid]
  228. def _iterencode_default(self, o, markers=None):
  229. newobj = self.default(o)
  230. return self._iterencode(newobj, markers)
  231. def default(self, o):
  232. """
  233. Implement this method in a subclass such that it returns
  234. a serializable object for ``o``, or calls the base implementation
  235. (to raise a ``TypeError``).
  236. For example, to support arbitrary iterators, you could
  237. implement default like this::
  238. def default(self, o):
  239. try:
  240. iterable = iter(o)
  241. except TypeError:
  242. pass
  243. else:
  244. return list(iterable)
  245. return JSONEncoder.default(self, o)
  246. """
  247. raise TypeError("%r is not JSON serializable" % (o,))
  248. def encode(self, o):
  249. """
  250. Return a JSON string representation of a Python data structure.
  251. >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  252. '{"foo":["bar", "baz"]}'
  253. """
  254. # This doesn't pass the iterator directly to ''.join() because it
  255. # sucks at reporting exceptions. It's going to do this internally
  256. # anyway because it uses PySequence_Fast or similar.
  257. chunks = list(self.iterencode(o))
  258. return ''.join(chunks)
  259. def iterencode(self, o):
  260. """
  261. Encode the given object and yield each string
  262. representation as available.
  263. For example::
  264. for chunk in JSONEncoder().iterencode(bigobject):
  265. mysocket.write(chunk)
  266. """
  267. if self.check_circular:
  268. markers = {}
  269. else:
  270. markers = None
  271. return self._iterencode(o, markers)
  272. __all__ = ['JSONEncoder']