PageRenderTime 40ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/vanl/pypy
Python | 538 lines | 437 code | 21 blank | 80 comment | 79 complexity | 7698ec9224756619174843d84755d12b MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, AGPL-3.0
  1. """Implementation of JSONEncoder
  2. """
  3. import re
  4. from __pypy__.builders import StringBuilder, UnicodeBuilder
  5. class StringOrUnicodeBuilder(object):
  6. def __init__(self):
  7. self._builder = StringBuilder()
  8. def append(self, string):
  9. try:
  10. self._builder.append(string)
  11. except UnicodeEncodeError:
  12. ub = UnicodeBuilder()
  13. ub.append(self._builder.build())
  14. self._builder = ub
  15. ub.append(string)
  16. def build(self):
  17. return self._builder.build()
  18. ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
  19. ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
  20. HAS_UTF8 = re.compile(r'[\x80-\xff]')
  21. ESCAPE_DCT = {
  22. '\\': '\\\\',
  23. '"': '\\"',
  24. '\b': '\\b',
  25. '\f': '\\f',
  26. '\n': '\\n',
  27. '\r': '\\r',
  28. '\t': '\\t',
  29. }
  30. for i in range(0x20):
  31. ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
  32. INFINITY = float('inf')
  33. FLOAT_REPR = repr
  34. def raw_encode_basestring(s):
  35. """Return a JSON representation of a Python string
  36. """
  37. def replace(match):
  38. return ESCAPE_DCT[match.group(0)]
  39. return ESCAPE.sub(replace, s)
  40. encode_basestring = lambda s: '"' + raw_encode_basestring(s) + '"'
  41. def raw_encode_basestring_ascii(s):
  42. """Return an ASCII-only JSON representation of a Python string
  43. """
  44. if isinstance(s, str) and HAS_UTF8.search(s) is not None:
  45. s = s.decode('utf-8')
  46. def replace(match):
  47. s = match.group(0)
  48. try:
  49. return ESCAPE_DCT[s]
  50. except KeyError:
  51. n = ord(s)
  52. if n < 0x10000:
  53. return '\\u%04x' % (n,)
  54. else:
  55. # surrogate pair
  56. n -= 0x10000
  57. s1 = 0xd800 | ((n >> 10) & 0x3ff)
  58. s2 = 0xdc00 | (n & 0x3ff)
  59. return '\\u%04x\\u%04x' % (s1, s2)
  60. if ESCAPE_ASCII.search(s):
  61. return str(ESCAPE_ASCII.sub(replace, s))
  62. return s
  63. encode_basestring_ascii = lambda s: '"' + raw_encode_basestring_ascii(s) + '"'
  64. class JSONEncoder(object):
  65. """Extensible JSON <http://json.org> encoder for Python data structures.
  66. Supports the following objects and types by default:
  67. +-------------------+---------------+
  68. | Python | JSON |
  69. +===================+===============+
  70. | dict | object |
  71. +-------------------+---------------+
  72. | list, tuple | array |
  73. +-------------------+---------------+
  74. | str, unicode | string |
  75. +-------------------+---------------+
  76. | int, long, float | number |
  77. +-------------------+---------------+
  78. | True | true |
  79. +-------------------+---------------+
  80. | False | false |
  81. +-------------------+---------------+
  82. | None | null |
  83. +-------------------+---------------+
  84. To extend this to recognize other objects, subclass and implement a
  85. ``.default()`` method with another method that returns a serializable
  86. object for ``o`` if possible, otherwise it should call the superclass
  87. implementation (to raise ``TypeError``).
  88. """
  89. item_separator = ', '
  90. key_separator = ': '
  91. def __init__(self, skipkeys=False, ensure_ascii=True,
  92. check_circular=True, allow_nan=True, sort_keys=False,
  93. indent=None, separators=None, encoding='utf-8', default=None):
  94. """Constructor for JSONEncoder, with sensible defaults.
  95. If skipkeys is false, then it is a TypeError to attempt
  96. encoding of keys that are not str, int, long, float or None. If
  97. skipkeys is True, such items are simply skipped.
  98. If *ensure_ascii* is true (the default), all non-ASCII
  99. characters in the output are escaped with \uXXXX sequences,
  100. and the results are str instances consisting of ASCII
  101. characters only. If ensure_ascii is False, a result may be a
  102. unicode instance. This usually happens if the input contains
  103. unicode strings or the *encoding* parameter is used.
  104. If check_circular is true, then lists, dicts, and custom encoded
  105. objects will be checked for circular references during encoding to
  106. prevent an infinite recursion (which would cause an OverflowError).
  107. Otherwise, no such check takes place.
  108. If allow_nan is true, then NaN, Infinity, and -Infinity will be
  109. encoded as such. This behavior is not JSON specification compliant,
  110. but is consistent with most JavaScript based encoders and decoders.
  111. Otherwise, it will be a ValueError to encode such floats.
  112. If sort_keys is true, then the output of dictionaries will be
  113. sorted by key; this is useful for regression tests to ensure
  114. that JSON serializations can be compared on a day-to-day basis.
  115. If indent is a non-negative integer, then JSON array
  116. elements and object members will be pretty-printed with that
  117. indent level. An indent level of 0 will only insert newlines.
  118. None is the most compact representation. Since the default
  119. item separator is ', ', the output might include trailing
  120. whitespace when indent is specified. You can use
  121. separators=(',', ': ') to avoid this.
  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. if ensure_ascii:
  135. self.__encoder = raw_encode_basestring_ascii
  136. else:
  137. self.__encoder = raw_encode_basestring
  138. if encoding != 'utf-8':
  139. orig_encoder = self.__encoder
  140. def encoder(o):
  141. if isinstance(o, str):
  142. o = o.decode(encoding)
  143. return orig_encoder(o)
  144. self.__encoder = encoder
  145. self.check_circular = check_circular
  146. self.allow_nan = allow_nan
  147. self.sort_keys = sort_keys
  148. self.indent = indent
  149. if separators is not None:
  150. self.item_separator, self.key_separator = separators
  151. if default is not None:
  152. self.default = default
  153. self.encoding = encoding
  154. def default(self, o):
  155. """Implement this method in a subclass such that it returns
  156. a serializable object for ``o``, or calls the base implementation
  157. (to raise a ``TypeError``).
  158. For example, to support arbitrary iterators, you could
  159. implement default like this::
  160. def default(self, o):
  161. try:
  162. iterable = iter(o)
  163. except TypeError:
  164. pass
  165. else:
  166. return list(iterable)
  167. # Let the base class default method raise the TypeError
  168. return JSONEncoder.default(self, o)
  169. """
  170. raise TypeError(repr(o) + " is not JSON serializable")
  171. def encode(self, o):
  172. """Return a JSON string representation of a Python data structure.
  173. >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  174. '{"foo": ["bar", "baz"]}'
  175. """
  176. if self.check_circular:
  177. markers = {}
  178. else:
  179. markers = None
  180. if self.ensure_ascii:
  181. builder = StringBuilder()
  182. else:
  183. builder = StringOrUnicodeBuilder()
  184. self.__encode(o, markers, builder, 0)
  185. return builder.build()
  186. def __emit_indent(self, builder, _current_indent_level):
  187. if self.indent is not None:
  188. _current_indent_level += 1
  189. newline_indent = '\n' + (' ' * (self.indent *
  190. _current_indent_level))
  191. separator = self.item_separator + newline_indent
  192. builder.append(newline_indent)
  193. else:
  194. separator = self.item_separator
  195. return separator, _current_indent_level
  196. def __emit_unindent(self, builder, _current_indent_level):
  197. if self.indent is not None:
  198. builder.append('\n')
  199. builder.append(' ' * (self.indent * (_current_indent_level - 1)))
  200. def __encode(self, o, markers, builder, _current_indent_level):
  201. if isinstance(o, basestring):
  202. builder.append('"')
  203. builder.append(self.__encoder(o))
  204. builder.append('"')
  205. elif o is None:
  206. builder.append('null')
  207. elif o is True:
  208. builder.append('true')
  209. elif o is False:
  210. builder.append('false')
  211. elif isinstance(o, (int, long)):
  212. builder.append(str(o))
  213. elif isinstance(o, float):
  214. builder.append(self.__floatstr(o))
  215. elif isinstance(o, (list, tuple)):
  216. if not o:
  217. builder.append('[]')
  218. return
  219. self.__encode_list(o, markers, builder, _current_indent_level)
  220. elif isinstance(o, dict):
  221. if not o:
  222. builder.append('{}')
  223. return
  224. self.__encode_dict(o, markers, builder, _current_indent_level)
  225. else:
  226. self.__mark_markers(markers, o)
  227. res = self.default(o)
  228. self.__encode(res, markers, builder, _current_indent_level)
  229. self.__remove_markers(markers, o)
  230. return res
  231. def __encode_list(self, l, markers, builder, _current_indent_level):
  232. self.__mark_markers(markers, l)
  233. builder.append('[')
  234. first = True
  235. separator, _current_indent_level = self.__emit_indent(builder,
  236. _current_indent_level)
  237. for elem in l:
  238. if first:
  239. first = False
  240. else:
  241. builder.append(separator)
  242. self.__encode(elem, markers, builder, _current_indent_level)
  243. del elem # XXX grumble
  244. self.__emit_unindent(builder, _current_indent_level)
  245. builder.append(']')
  246. self.__remove_markers(markers, l)
  247. def __encode_dict(self, d, markers, builder, _current_indent_level):
  248. self.__mark_markers(markers, d)
  249. first = True
  250. builder.append('{')
  251. separator, _current_indent_level = self.__emit_indent(builder,
  252. _current_indent_level)
  253. if self.sort_keys:
  254. items = sorted(d.items(), key=lambda kv: kv[0])
  255. else:
  256. items = d.iteritems()
  257. for key, v in items:
  258. if first:
  259. first = False
  260. else:
  261. builder.append(separator)
  262. if isinstance(key, basestring):
  263. pass
  264. # JavaScript is weakly typed for these, so it makes sense to
  265. # also allow them. Many encoders seem to do something like this.
  266. elif isinstance(key, float):
  267. key = self.__floatstr(key)
  268. elif key is True:
  269. key = 'true'
  270. elif key is False:
  271. key = 'false'
  272. elif key is None:
  273. key = 'null'
  274. elif isinstance(key, (int, long)):
  275. key = str(key)
  276. elif self.skipkeys:
  277. continue
  278. else:
  279. raise TypeError("key " + repr(key) + " is not a string")
  280. builder.append('"')
  281. builder.append(self.__encoder(key))
  282. builder.append('"')
  283. builder.append(self.key_separator)
  284. self.__encode(v, markers, builder, _current_indent_level)
  285. del key
  286. del v # XXX grumble
  287. self.__emit_unindent(builder, _current_indent_level)
  288. builder.append('}')
  289. self.__remove_markers(markers, d)
  290. def iterencode(self, o, _one_shot=False):
  291. """Encode the given object and yield each string
  292. representation as available.
  293. For example::
  294. for chunk in JSONEncoder().iterencode(bigobject):
  295. mysocket.write(chunk)
  296. """
  297. if self.check_circular:
  298. markers = {}
  299. else:
  300. markers = None
  301. return self.__iterencode(o, markers, 0)
  302. def __floatstr(self, o):
  303. # Check for specials. Note that this type of test is processor
  304. # and/or platform-specific, so do tests which don't depend on the
  305. # internals.
  306. if o != o:
  307. text = 'NaN'
  308. elif o == INFINITY:
  309. text = 'Infinity'
  310. elif o == -INFINITY:
  311. text = '-Infinity'
  312. else:
  313. return FLOAT_REPR(o)
  314. if not self.allow_nan:
  315. raise ValueError(
  316. "Out of range float values are not JSON compliant: " +
  317. repr(o))
  318. return text
  319. def __mark_markers(self, markers, o):
  320. if markers is not None:
  321. if id(o) in markers:
  322. raise ValueError("Circular reference detected")
  323. markers[id(o)] = None
  324. def __remove_markers(self, markers, o):
  325. if markers is not None:
  326. del markers[id(o)]
  327. def __iterencode_list(self, lst, markers, _current_indent_level):
  328. if not lst:
  329. yield '[]'
  330. return
  331. self.__mark_markers(markers, lst)
  332. buf = '['
  333. if self.indent is not None:
  334. _current_indent_level += 1
  335. newline_indent = '\n' + (' ' * (self.indent *
  336. _current_indent_level))
  337. separator = self.item_separator + newline_indent
  338. buf += newline_indent
  339. else:
  340. newline_indent = None
  341. separator = self.item_separator
  342. first = True
  343. for value in lst:
  344. if first:
  345. first = False
  346. else:
  347. buf = separator
  348. if isinstance(value, basestring):
  349. yield buf + '"' + self.__encoder(value) + '"'
  350. elif value is None:
  351. yield buf + 'null'
  352. elif value is True:
  353. yield buf + 'true'
  354. elif value is False:
  355. yield buf + 'false'
  356. elif isinstance(value, (int, long)):
  357. yield buf + str(value)
  358. elif isinstance(value, float):
  359. yield buf + self.__floatstr(value)
  360. else:
  361. yield buf
  362. if isinstance(value, (list, tuple)):
  363. chunks = self.__iterencode_list(value, markers,
  364. _current_indent_level)
  365. elif isinstance(value, dict):
  366. chunks = self.__iterencode_dict(value, markers,
  367. _current_indent_level)
  368. else:
  369. chunks = self.__iterencode(value, markers,
  370. _current_indent_level)
  371. for chunk in chunks:
  372. yield chunk
  373. if newline_indent is not None:
  374. _current_indent_level -= 1
  375. yield '\n' + (' ' * (self.indent * _current_indent_level))
  376. yield ']'
  377. self.__remove_markers(markers, lst)
  378. def __iterencode_dict(self, dct, markers, _current_indent_level):
  379. if not dct:
  380. yield '{}'
  381. return
  382. self.__mark_markers(markers, dct)
  383. yield '{'
  384. if self.indent is not None:
  385. _current_indent_level += 1
  386. newline_indent = '\n' + (' ' * (self.indent *
  387. _current_indent_level))
  388. item_separator = self.item_separator + newline_indent
  389. yield newline_indent
  390. else:
  391. newline_indent = None
  392. item_separator = self.item_separator
  393. first = True
  394. if self.sort_keys:
  395. items = sorted(dct.items(), key=lambda kv: kv[0])
  396. else:
  397. items = dct.iteritems()
  398. for key, value in items:
  399. if isinstance(key, basestring):
  400. pass
  401. # JavaScript is weakly typed for these, so it makes sense to
  402. # also allow them. Many encoders seem to do something like this.
  403. elif isinstance(key, float):
  404. key = self.__floatstr(key)
  405. elif key is True:
  406. key = 'true'
  407. elif key is False:
  408. key = 'false'
  409. elif key is None:
  410. key = 'null'
  411. elif isinstance(key, (int, long)):
  412. key = str(key)
  413. elif self.skipkeys:
  414. continue
  415. else:
  416. raise TypeError("key " + repr(key) + " is not a string")
  417. if first:
  418. first = False
  419. else:
  420. yield item_separator
  421. yield '"' + self.__encoder(key) + '"'
  422. yield self.key_separator
  423. if isinstance(value, basestring):
  424. yield '"' + self.__encoder(value) + '"'
  425. elif value is None:
  426. yield 'null'
  427. elif value is True:
  428. yield 'true'
  429. elif value is False:
  430. yield 'false'
  431. elif isinstance(value, (int, long)):
  432. yield str(value)
  433. elif isinstance(value, float):
  434. yield self.__floatstr(value)
  435. else:
  436. if isinstance(value, (list, tuple)):
  437. chunks = self.__iterencode_list(value, markers,
  438. _current_indent_level)
  439. elif isinstance(value, dict):
  440. chunks = self.__iterencode_dict(value, markers,
  441. _current_indent_level)
  442. else:
  443. chunks = self.__iterencode(value, markers,
  444. _current_indent_level)
  445. for chunk in chunks:
  446. yield chunk
  447. if newline_indent is not None:
  448. _current_indent_level -= 1
  449. yield '\n' + (' ' * (self.indent * _current_indent_level))
  450. yield '}'
  451. self.__remove_markers(markers, dct)
  452. def __iterencode(self, o, markers, _current_indent_level):
  453. if isinstance(o, basestring):
  454. yield '"' + self.__encoder(o) + '"'
  455. elif o is None:
  456. yield 'null'
  457. elif o is True:
  458. yield 'true'
  459. elif o is False:
  460. yield 'false'
  461. elif isinstance(o, (int, long)):
  462. yield str(o)
  463. elif isinstance(o, float):
  464. yield self.__floatstr(o)
  465. elif isinstance(o, (list, tuple)):
  466. for chunk in self.__iterencode_list(o, markers,
  467. _current_indent_level):
  468. yield chunk
  469. elif isinstance(o, dict):
  470. for chunk in self.__iterencode_dict(o, markers,
  471. _current_indent_level):
  472. yield chunk
  473. else:
  474. self.__mark_markers(markers, o)
  475. obj = self.default(o)
  476. for chunk in self.__iterencode(obj, markers,
  477. _current_indent_level):
  478. yield chunk
  479. self.__remove_markers(markers, o)
  480. # overwrite some helpers here with more efficient versions
  481. try:
  482. from _pypyjson import raw_encode_basestring_ascii
  483. except ImportError:
  484. pass