PageRenderTime 63ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/json/encoder.py

https://bitbucket.org/kkris/pypy
Python | 510 lines | 414 code | 17 blank | 79 comment | 75 complexity | 8b3329b1ab6b1172c4ee744b660c7cb9 MD5 | raw file
  1. """Implementation of JSONEncoder
  2. """
  3. import re
  4. from __pypy__.builders import StringBuilder, UnicodeBuilder
  5. ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
  6. ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
  7. HAS_UTF8 = re.compile(r'[\x80-\xff]')
  8. ESCAPE_DCT = {
  9. '\\': '\\\\',
  10. '"': '\\"',
  11. '\b': '\\b',
  12. '\f': '\\f',
  13. '\n': '\\n',
  14. '\r': '\\r',
  15. '\t': '\\t',
  16. }
  17. for i in range(0x20):
  18. ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
  19. # Assume this produces an infinity on all machines (probably not guaranteed)
  20. INFINITY = float('1e66666')
  21. FLOAT_REPR = repr
  22. def raw_encode_basestring(s):
  23. """Return a JSON representation of a Python string
  24. """
  25. def replace(match):
  26. return ESCAPE_DCT[match.group(0)]
  27. return ESCAPE.sub(replace, s)
  28. encode_basestring = lambda s: '"' + raw_encode_basestring(s) + '"'
  29. def raw_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. if ESCAPE_ASCII.search(s):
  49. return str(ESCAPE_ASCII.sub(replace, s))
  50. return s
  51. encode_basestring_ascii = lambda s: '"' + raw_encode_basestring_ascii(s) + '"'
  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. if ensure_ascii:
  117. self.encoder = raw_encode_basestring_ascii
  118. else:
  119. self.encoder = raw_encode_basestring
  120. if encoding != 'utf-8':
  121. orig_encoder = self.encoder
  122. def encoder(o):
  123. if isinstance(o, str):
  124. o = o.decode(encoding)
  125. return orig_encoder(o)
  126. self.encoder = encoder
  127. self.check_circular = check_circular
  128. self.allow_nan = allow_nan
  129. self.sort_keys = sort_keys
  130. self.indent = indent
  131. if separators is not None:
  132. self.item_separator, self.key_separator = separators
  133. if default is not None:
  134. self.default = default
  135. self.encoding = encoding
  136. def default(self, o):
  137. """Implement this method in a subclass such that it returns
  138. a serializable object for ``o``, or calls the base implementation
  139. (to raise a ``TypeError``).
  140. For example, to support arbitrary iterators, you could
  141. implement default like this::
  142. def default(self, o):
  143. try:
  144. iterable = iter(o)
  145. except TypeError:
  146. pass
  147. else:
  148. return list(iterable)
  149. return JSONEncoder.default(self, o)
  150. """
  151. raise TypeError(repr(o) + " is not JSON serializable")
  152. def encode(self, o):
  153. """Return a JSON string representation of a Python data structure.
  154. >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  155. '{"foo": ["bar", "baz"]}'
  156. """
  157. if self.check_circular:
  158. markers = {}
  159. else:
  160. markers = None
  161. if self.ensure_ascii:
  162. builder = StringBuilder()
  163. else:
  164. builder = UnicodeBuilder()
  165. self._encode(o, markers, builder, 0)
  166. return builder.build()
  167. def _emit_indent(self, builder, _current_indent_level):
  168. if self.indent is not None:
  169. _current_indent_level += 1
  170. newline_indent = '\n' + (' ' * (self.indent *
  171. _current_indent_level))
  172. separator = self.item_separator + newline_indent
  173. builder.append(newline_indent)
  174. else:
  175. separator = self.item_separator
  176. return separator, _current_indent_level
  177. def _emit_unindent(self, builder, _current_indent_level):
  178. if self.indent is not None:
  179. builder.append('\n')
  180. builder.append(' ' * (self.indent * (_current_indent_level - 1)))
  181. def _encode(self, o, markers, builder, _current_indent_level):
  182. if isinstance(o, basestring):
  183. builder.append('"')
  184. builder.append(self.encoder(o))
  185. builder.append('"')
  186. elif o is None:
  187. builder.append('null')
  188. elif o is True:
  189. builder.append('true')
  190. elif o is False:
  191. builder.append('false')
  192. elif isinstance(o, (int, long)):
  193. builder.append(str(o))
  194. elif isinstance(o, float):
  195. builder.append(self._floatstr(o))
  196. elif isinstance(o, (list, tuple)):
  197. if not o:
  198. builder.append('[]')
  199. return
  200. self._encode_list(o, markers, builder, _current_indent_level)
  201. elif isinstance(o, dict):
  202. if not o:
  203. builder.append('{}')
  204. return
  205. self._encode_dict(o, markers, builder, _current_indent_level)
  206. else:
  207. self._mark_markers(markers, o)
  208. res = self.default(o)
  209. self._encode(res, markers, builder, _current_indent_level)
  210. self._remove_markers(markers, o)
  211. return res
  212. def _encode_list(self, l, markers, builder, _current_indent_level):
  213. self._mark_markers(markers, l)
  214. builder.append('[')
  215. first = True
  216. separator, _current_indent_level = self._emit_indent(builder,
  217. _current_indent_level)
  218. for elem in l:
  219. if first:
  220. first = False
  221. else:
  222. builder.append(separator)
  223. self._encode(elem, markers, builder, _current_indent_level)
  224. del elem # XXX grumble
  225. self._emit_unindent(builder, _current_indent_level)
  226. builder.append(']')
  227. self._remove_markers(markers, l)
  228. def _encode_dict(self, d, markers, builder, _current_indent_level):
  229. self._mark_markers(markers, d)
  230. first = True
  231. builder.append('{')
  232. separator, _current_indent_level = self._emit_indent(builder,
  233. _current_indent_level)
  234. if self.sort_keys:
  235. items = sorted(d.items(), key=lambda kv: kv[0])
  236. else:
  237. items = d.iteritems()
  238. for key, v in items:
  239. if first:
  240. first = False
  241. else:
  242. builder.append(separator)
  243. if isinstance(key, basestring):
  244. pass
  245. # JavaScript is weakly typed for these, so it makes sense to
  246. # also allow them. Many encoders seem to do something like this.
  247. elif isinstance(key, float):
  248. key = self._floatstr(key)
  249. elif key is True:
  250. key = 'true'
  251. elif key is False:
  252. key = 'false'
  253. elif key is None:
  254. key = 'null'
  255. elif isinstance(key, (int, long)):
  256. key = str(key)
  257. elif self.skipkeys:
  258. continue
  259. else:
  260. raise TypeError("key " + repr(key) + " is not a string")
  261. builder.append('"')
  262. builder.append(self.encoder(key))
  263. builder.append('"')
  264. builder.append(self.key_separator)
  265. self._encode(v, markers, builder, _current_indent_level)
  266. del key
  267. del v # XXX grumble
  268. self._emit_unindent(builder, _current_indent_level)
  269. builder.append('}')
  270. self._remove_markers(markers, d)
  271. def iterencode(self, o, _one_shot=False):
  272. """Encode the given object and yield each string
  273. representation as available.
  274. For example::
  275. for chunk in JSONEncoder().iterencode(bigobject):
  276. mysocket.write(chunk)
  277. """
  278. if self.check_circular:
  279. markers = {}
  280. else:
  281. markers = None
  282. return self._iterencode(o, markers, 0)
  283. def _floatstr(self, o):
  284. # Check for specials. Note that this type of test is processor
  285. # and/or platform-specific, so do tests which don't depend on the
  286. # internals.
  287. if o != o:
  288. text = 'NaN'
  289. elif o == INFINITY:
  290. text = 'Infinity'
  291. elif o == -INFINITY:
  292. text = '-Infinity'
  293. else:
  294. return FLOAT_REPR(o)
  295. if not self.allow_nan:
  296. raise ValueError(
  297. "Out of range float values are not JSON compliant: " +
  298. repr(o))
  299. return text
  300. def _mark_markers(self, markers, o):
  301. if markers is not None:
  302. if id(o) in markers:
  303. raise ValueError("Circular reference detected")
  304. markers[id(o)] = None
  305. def _remove_markers(self, markers, o):
  306. if markers is not None:
  307. del markers[id(o)]
  308. def _iterencode_list(self, lst, markers, _current_indent_level):
  309. if not lst:
  310. yield '[]'
  311. return
  312. self._mark_markers(markers, lst)
  313. buf = '['
  314. if self.indent is not None:
  315. _current_indent_level += 1
  316. newline_indent = '\n' + (' ' * (self.indent *
  317. _current_indent_level))
  318. separator = self.item_separator + newline_indent
  319. buf += newline_indent
  320. else:
  321. newline_indent = None
  322. separator = self.item_separator
  323. first = True
  324. for value in lst:
  325. if first:
  326. first = False
  327. else:
  328. buf = separator
  329. if isinstance(value, basestring):
  330. yield buf + '"' + self.encoder(value) + '"'
  331. elif value is None:
  332. yield buf + 'null'
  333. elif value is True:
  334. yield buf + 'true'
  335. elif value is False:
  336. yield buf + 'false'
  337. elif isinstance(value, (int, long)):
  338. yield buf + str(value)
  339. elif isinstance(value, float):
  340. yield buf + self._floatstr(value)
  341. else:
  342. yield buf
  343. if isinstance(value, (list, tuple)):
  344. chunks = self._iterencode_list(value, markers,
  345. _current_indent_level)
  346. elif isinstance(value, dict):
  347. chunks = self._iterencode_dict(value, markers,
  348. _current_indent_level)
  349. else:
  350. chunks = self._iterencode(value, markers,
  351. _current_indent_level)
  352. for chunk in chunks:
  353. yield chunk
  354. if newline_indent is not None:
  355. _current_indent_level -= 1
  356. yield '\n' + (' ' * (self.indent * _current_indent_level))
  357. yield ']'
  358. self._remove_markers(markers, lst)
  359. def _iterencode_dict(self, dct, markers, _current_indent_level):
  360. if not dct:
  361. yield '{}'
  362. return
  363. self._mark_markers(markers, dct)
  364. yield '{'
  365. if self.indent is not None:
  366. _current_indent_level += 1
  367. newline_indent = '\n' + (' ' * (self.indent *
  368. _current_indent_level))
  369. item_separator = self.item_separator + newline_indent
  370. yield newline_indent
  371. else:
  372. newline_indent = None
  373. item_separator = self.item_separator
  374. first = True
  375. if self.sort_keys:
  376. items = sorted(dct.items(), key=lambda kv: kv[0])
  377. else:
  378. items = dct.iteritems()
  379. for key, value in items:
  380. if isinstance(key, basestring):
  381. pass
  382. # JavaScript is weakly typed for these, so it makes sense to
  383. # also allow them. Many encoders seem to do something like this.
  384. elif isinstance(key, float):
  385. key = self._floatstr(key)
  386. elif key is True:
  387. key = 'true'
  388. elif key is False:
  389. key = 'false'
  390. elif key is None:
  391. key = 'null'
  392. elif isinstance(key, (int, long)):
  393. key = str(key)
  394. elif self.skipkeys:
  395. continue
  396. else:
  397. raise TypeError("key " + repr(key) + " is not a string")
  398. if first:
  399. first = False
  400. else:
  401. yield item_separator
  402. yield '"' + self.encoder(key) + '"'
  403. yield self.key_separator
  404. if isinstance(value, basestring):
  405. yield '"' + self.encoder(value) + '"'
  406. elif value is None:
  407. yield 'null'
  408. elif value is True:
  409. yield 'true'
  410. elif value is False:
  411. yield 'false'
  412. elif isinstance(value, (int, long)):
  413. yield str(value)
  414. elif isinstance(value, float):
  415. yield self._floatstr(value)
  416. else:
  417. if isinstance(value, (list, tuple)):
  418. chunks = self._iterencode_list(value, markers,
  419. _current_indent_level)
  420. elif isinstance(value, dict):
  421. chunks = self._iterencode_dict(value, markers,
  422. _current_indent_level)
  423. else:
  424. chunks = self._iterencode(value, markers,
  425. _current_indent_level)
  426. for chunk in chunks:
  427. yield chunk
  428. if newline_indent is not None:
  429. _current_indent_level -= 1
  430. yield '\n' + (' ' * (self.indent * _current_indent_level))
  431. yield '}'
  432. self._remove_markers(markers, dct)
  433. def _iterencode(self, o, markers, _current_indent_level):
  434. if isinstance(o, basestring):
  435. yield '"' + self.encoder(o) + '"'
  436. elif o is None:
  437. yield 'null'
  438. elif o is True:
  439. yield 'true'
  440. elif o is False:
  441. yield 'false'
  442. elif isinstance(o, (int, long)):
  443. yield str(o)
  444. elif isinstance(o, float):
  445. yield self._floatstr(o)
  446. elif isinstance(o, (list, tuple)):
  447. for chunk in self._iterencode_list(o, markers,
  448. _current_indent_level):
  449. yield chunk
  450. elif isinstance(o, dict):
  451. for chunk in self._iterencode_dict(o, markers,
  452. _current_indent_level):
  453. yield chunk
  454. else:
  455. self._mark_markers(markers, o)
  456. obj = self.default(o)
  457. for chunk in self._iterencode(obj, markers,
  458. _current_indent_level):
  459. yield chunk
  460. self._remove_markers(markers, o)