/Lib/json/encoder.py

http://unladen-swallow.googlecode.com/ · Python · 384 lines · 272 code · 20 blank · 92 comment · 20 complexity · 3550688516110f12336a52f12cee7c3c MD5 · raw file

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