PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/json/encoder.py

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