PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/simplejson/encoder.py

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