PageRenderTime 26ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/utils/simplejson/encoder.py

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