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

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

https://bitbucket.org/pwaller/pypy
Python | 385 lines | 353 code | 14 blank | 18 comment | 13 complexity | 863a55a76a548a465a7dbaa8b8f06c5c MD5 | raw file
  1. """Implementation of JSONDecoder
  2. """
  3. import re
  4. import sys
  5. import struct
  6. from json import scanner
  7. try:
  8. from _json import scanstring as c_scanstring
  9. except ImportError:
  10. c_scanstring = None
  11. __all__ = ['JSONDecoder']
  12. FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
  13. def _floatconstants():
  14. _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
  15. if sys.byteorder != 'big':
  16. _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
  17. nan, inf = struct.unpack('dd', _BYTES)
  18. return nan, inf, -inf
  19. NaN, PosInf, NegInf = _floatconstants()
  20. def linecol(doc, pos):
  21. lineno = doc.count('\n', 0, pos) + 1
  22. if lineno == 1:
  23. colno = pos
  24. else:
  25. colno = pos - doc.rindex('\n', 0, pos)
  26. return lineno, colno
  27. def errmsg(msg, doc, pos, end=None):
  28. # Note that this function is called from _json
  29. lineno, colno = linecol(doc, pos)
  30. if end is None:
  31. fmt = '{0}: line {1} column {2} (char {3})'
  32. return fmt.format(msg, lineno, colno, pos)
  33. #fmt = '%s: line %d column %d (char %d)'
  34. #return fmt % (msg, lineno, colno, pos)
  35. endlineno, endcolno = linecol(doc, end)
  36. fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
  37. return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
  38. #fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
  39. #return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
  40. _CONSTANTS = {
  41. '-Infinity': NegInf,
  42. 'Infinity': PosInf,
  43. 'NaN': NaN,
  44. }
  45. STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
  46. BACKSLASH = {
  47. '"': u'"', '\\': u'\\', '/': u'/',
  48. 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
  49. }
  50. DEFAULT_ENCODING = "utf-8"
  51. def py_scanstring(s, end, encoding=None, strict=True,
  52. _b=BACKSLASH, _m=STRINGCHUNK.match):
  53. """Scan the string s for a JSON string. End is the index of the
  54. character in s after the quote that started the JSON string.
  55. Unescapes all valid JSON string escape sequences and raises ValueError
  56. on attempt to decode an invalid string. If strict is False then literal
  57. control characters are allowed in the string.
  58. Returns a tuple of the decoded string and the index of the character in s
  59. after the end quote."""
  60. if encoding is None:
  61. encoding = DEFAULT_ENCODING
  62. chunks = []
  63. _append = chunks.append
  64. begin = end - 1
  65. while 1:
  66. chunk = _m(s, end)
  67. if chunk is None:
  68. raise ValueError(
  69. errmsg("Unterminated string starting at", s, begin))
  70. end = chunk.end()
  71. content, terminator = chunk.groups()
  72. # Content is contains zero or more unescaped string characters
  73. if content:
  74. if not isinstance(content, unicode):
  75. content = unicode(content, encoding)
  76. _append(content)
  77. # Terminator is the end of string, a literal control character,
  78. # or a backslash denoting that an escape sequence follows
  79. if terminator == '"':
  80. break
  81. elif terminator != '\\':
  82. if strict:
  83. #msg = "Invalid control character %r at" % (terminator,)
  84. msg = "Invalid control character {0!r} at".format(terminator)
  85. raise ValueError(errmsg(msg, s, end))
  86. else:
  87. _append(terminator)
  88. continue
  89. try:
  90. esc = s[end]
  91. except IndexError:
  92. raise ValueError(
  93. errmsg("Unterminated string starting at", s, begin))
  94. # If not a unicode escape sequence, must be in the lookup table
  95. if esc != 'u':
  96. try:
  97. char = _b[esc]
  98. except KeyError:
  99. msg = "Invalid \\escape: " + repr(esc)
  100. raise ValueError(errmsg(msg, s, end))
  101. end += 1
  102. else:
  103. # Unicode escape sequence
  104. esc = s[end + 1:end + 5]
  105. next_end = end + 5
  106. if len(esc) != 4:
  107. msg = "Invalid \\uXXXX escape"
  108. raise ValueError(errmsg(msg, s, end))
  109. uni = int(esc, 16)
  110. # Check for surrogate pair on UCS-4 systems
  111. if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
  112. msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
  113. if not s[end + 5:end + 7] == '\\u':
  114. raise ValueError(errmsg(msg, s, end))
  115. esc2 = s[end + 7:end + 11]
  116. if len(esc2) != 4:
  117. raise ValueError(errmsg(msg, s, end))
  118. uni2 = int(esc2, 16)
  119. uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
  120. next_end += 6
  121. char = unichr(uni)
  122. end = next_end
  123. # Append the unescaped character
  124. _append(char)
  125. return u''.join(chunks), end
  126. # Use speedup if available
  127. scanstring = c_scanstring or py_scanstring
  128. WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
  129. WHITESPACE_STR = ' \t\n\r'
  130. def JSONObject(s_and_end, encoding, strict, scan_once, object_hook,
  131. object_pairs_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
  132. s, end = s_and_end
  133. pairs = []
  134. pairs_append = pairs.append
  135. # Use a slice to prevent IndexError from being raised, the following
  136. # check will raise a more specific ValueError if the string is empty
  137. nextchar = s[end:end + 1]
  138. # Normally we expect nextchar == '"'
  139. if nextchar != '"':
  140. if nextchar in _ws:
  141. end = _w(s, end).end()
  142. nextchar = s[end:end + 1]
  143. # Trivial empty object
  144. if nextchar == '}':
  145. if object_pairs_hook is not None:
  146. result = object_pairs_hook(pairs)
  147. return result, end
  148. pairs = {}
  149. if object_hook is not None:
  150. pairs = object_hook(pairs)
  151. return pairs, end + 1
  152. elif nextchar != '"':
  153. raise ValueError(errmsg("Expecting property name", s, end))
  154. end += 1
  155. while True:
  156. key, end = scanstring(s, end, encoding, strict)
  157. # To skip some function call overhead we optimize the fast paths where
  158. # the JSON key separator is ": " or just ":".
  159. if s[end:end + 1] != ':':
  160. end = _w(s, end).end()
  161. if s[end:end + 1] != ':':
  162. raise ValueError(errmsg("Expecting : delimiter", s, end))
  163. end += 1
  164. try:
  165. if s[end] in _ws:
  166. end += 1
  167. if s[end] in _ws:
  168. end = _w(s, end + 1).end()
  169. except IndexError:
  170. pass
  171. try:
  172. value, end = scan_once(s, end)
  173. except StopIteration:
  174. raise ValueError(errmsg("Expecting object", s, end))
  175. pairs_append((key, value))
  176. try:
  177. nextchar = s[end]
  178. if nextchar in _ws:
  179. end = _w(s, end + 1).end()
  180. nextchar = s[end]
  181. except IndexError:
  182. nextchar = ''
  183. end += 1
  184. if nextchar == '}':
  185. break
  186. elif nextchar != ',':
  187. raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
  188. try:
  189. nextchar = s[end]
  190. if nextchar in _ws:
  191. end += 1
  192. nextchar = s[end]
  193. if nextchar in _ws:
  194. end = _w(s, end + 1).end()
  195. nextchar = s[end]
  196. except IndexError:
  197. nextchar = ''
  198. end += 1
  199. if nextchar != '"':
  200. raise ValueError(errmsg("Expecting property name", s, end - 1))
  201. if object_pairs_hook is not None:
  202. result = object_pairs_hook(pairs)
  203. return result, end
  204. pairs = dict(pairs)
  205. if object_hook is not None:
  206. pairs = object_hook(pairs)
  207. return pairs, end
  208. def JSONArray(s_and_end, scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
  209. s, end = s_and_end
  210. values = []
  211. nextchar = s[end:end + 1]
  212. if nextchar in _ws:
  213. end = _w(s, end + 1).end()
  214. nextchar = s[end:end + 1]
  215. # Look-ahead for trivial empty array
  216. if nextchar == ']':
  217. return values, end + 1
  218. _append = values.append
  219. while True:
  220. try:
  221. value, end = scan_once(s, end)
  222. except StopIteration:
  223. raise ValueError(errmsg("Expecting object", s, end))
  224. _append(value)
  225. nextchar = s[end:end + 1]
  226. if nextchar in _ws:
  227. end = _w(s, end + 1).end()
  228. nextchar = s[end:end + 1]
  229. end += 1
  230. if nextchar == ']':
  231. break
  232. elif nextchar != ',':
  233. raise ValueError(errmsg("Expecting , delimiter", s, end))
  234. try:
  235. if s[end] in _ws:
  236. end += 1
  237. if s[end] in _ws:
  238. end = _w(s, end + 1).end()
  239. except IndexError:
  240. pass
  241. return values, end
  242. class JSONDecoder(object):
  243. """Simple JSON <http://json.org> decoder
  244. Performs the following translations in decoding by default:
  245. +---------------+-------------------+
  246. | JSON | Python |
  247. +===============+===================+
  248. | object | dict |
  249. +---------------+-------------------+
  250. | array | list |
  251. +---------------+-------------------+
  252. | string | unicode |
  253. +---------------+-------------------+
  254. | number (int) | int, long |
  255. +---------------+-------------------+
  256. | number (real) | float |
  257. +---------------+-------------------+
  258. | true | True |
  259. +---------------+-------------------+
  260. | false | False |
  261. +---------------+-------------------+
  262. | null | None |
  263. +---------------+-------------------+
  264. It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
  265. their corresponding ``float`` values, which is outside the JSON spec.
  266. """
  267. def __init__(self, encoding=None, object_hook=None, parse_float=None,
  268. parse_int=None, parse_constant=None, strict=True,
  269. object_pairs_hook=None):
  270. """``encoding`` determines the encoding used to interpret any ``str``
  271. objects decoded by this instance (utf-8 by default). It has no
  272. effect when decoding ``unicode`` objects.
  273. Note that currently only encodings that are a superset of ASCII work,
  274. strings of other encodings should be passed in as ``unicode``.
  275. ``object_hook``, if specified, will be called with the result
  276. of every JSON object decoded and its return value will be used in
  277. place of the given ``dict``. This can be used to provide custom
  278. deserializations (e.g. to support JSON-RPC class hinting).
  279. ``object_pairs_hook``, if specified will be called with the result of
  280. every JSON object decoded with an ordered list of pairs. The return
  281. value of ``object_pairs_hook`` will be used instead of the ``dict``.
  282. This feature can be used to implement custom decoders that rely on the
  283. order that the key and value pairs are decoded (for example,
  284. collections.OrderedDict will remember the order of insertion). If
  285. ``object_hook`` is also defined, the ``object_pairs_hook`` takes
  286. priority.
  287. ``parse_float``, if specified, will be called with the string
  288. of every JSON float to be decoded. By default this is equivalent to
  289. float(num_str). This can be used to use another datatype or parser
  290. for JSON floats (e.g. decimal.Decimal).
  291. ``parse_int``, if specified, will be called with the string
  292. of every JSON int to be decoded. By default this is equivalent to
  293. int(num_str). This can be used to use another datatype or parser
  294. for JSON integers (e.g. float).
  295. ``parse_constant``, if specified, will be called with one of the
  296. following strings: -Infinity, Infinity, NaN.
  297. This can be used to raise an exception if invalid JSON numbers
  298. are encountered.
  299. If ``strict`` is false (true is the default), then control
  300. characters will be allowed inside strings. Control characters in
  301. this context are those with character codes in the 0-31 range,
  302. including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.
  303. """
  304. self.encoding = encoding
  305. self.object_hook = object_hook
  306. self.object_pairs_hook = object_pairs_hook
  307. self.parse_float = parse_float or float
  308. self.parse_int = parse_int or int
  309. self.parse_constant = parse_constant or _CONSTANTS.__getitem__
  310. self.strict = strict
  311. self.parse_object = JSONObject
  312. self.parse_array = JSONArray
  313. self.parse_string = scanstring
  314. self.scan_once = scanner.make_scanner(self)
  315. def decode(self, s, _w=WHITESPACE.match):
  316. """Return the Python representation of ``s`` (a ``str`` or ``unicode``
  317. instance containing a JSON document)
  318. """
  319. obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  320. end = _w(s, end).end()
  321. if end != len(s):
  322. raise ValueError(errmsg("Extra data", s, end, len(s)))
  323. return obj
  324. def raw_decode(self, s, idx=0):
  325. """Decode a JSON document from ``s`` (a ``str`` or ``unicode``
  326. beginning with a JSON document) and return a 2-tuple of the Python
  327. representation and the index in ``s`` where the document ended.
  328. This can be used to decode a JSON document from a string that may
  329. have extraneous data at the end.
  330. """
  331. try:
  332. obj, end = self.scan_once(s, idx)
  333. except StopIteration:
  334. raise ValueError("No JSON object could be decoded")
  335. return obj, end