You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

370 lines
13 KiB

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