PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

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