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.

384 lines
14 KiB

  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(
  154. "Expecting property name enclosed in double quotes", s, end))
  155. end += 1
  156. while True:
  157. key, end = scanstring(s, end, encoding, strict)
  158. # To skip some function call overhead we optimize the fast paths where
  159. # the JSON key separator is ": " or just ":".
  160. if s[end:end + 1] != ':':
  161. end = _w(s, end).end()
  162. if s[end:end + 1] != ':':
  163. raise ValueError(errmsg("Expecting ':' delimiter", s, end))
  164. end += 1
  165. try:
  166. if s[end] in _ws:
  167. end += 1
  168. if s[end] in _ws:
  169. end = _w(s, end + 1).end()
  170. except IndexError:
  171. pass
  172. try:
  173. value, end = scan_once(s, end)
  174. except StopIteration:
  175. raise ValueError(errmsg("Expecting object", s, end))
  176. pairs_append((key, value))
  177. try:
  178. nextchar = s[end]
  179. if nextchar in _ws:
  180. end = _w(s, end + 1).end()
  181. nextchar = s[end]
  182. except IndexError:
  183. nextchar = ''
  184. end += 1
  185. if nextchar == '}':
  186. break
  187. elif nextchar != ',':
  188. raise ValueError(errmsg("Expecting ',' delimiter", s, end - 1))
  189. try:
  190. nextchar = s[end]
  191. if nextchar in _ws:
  192. end += 1
  193. nextchar = s[end]
  194. if nextchar in _ws:
  195. end = _w(s, end + 1).end()
  196. nextchar = s[end]
  197. except IndexError:
  198. nextchar = ''
  199. end += 1
  200. if nextchar != '"':
  201. raise ValueError(errmsg(
  202. "Expecting property name enclosed in double quotes", s, end - 1))
  203. if object_pairs_hook is not None:
  204. result = object_pairs_hook(pairs)
  205. return result, end
  206. pairs = dict(pairs)
  207. if object_hook is not None:
  208. pairs = object_hook(pairs)
  209. return pairs, end
  210. def JSONArray(s_and_end, scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
  211. s, end = s_and_end
  212. values = []
  213. nextchar = s[end:end + 1]
  214. if nextchar in _ws:
  215. end = _w(s, end + 1).end()
  216. nextchar = s[end:end + 1]
  217. # Look-ahead for trivial empty array
  218. if nextchar == ']':
  219. return values, end + 1
  220. _append = values.append
  221. while True:
  222. try:
  223. value, end = scan_once(s, end)
  224. except StopIteration:
  225. raise ValueError(errmsg("Expecting object", s, end))
  226. _append(value)
  227. nextchar = s[end:end + 1]
  228. if nextchar in _ws:
  229. end = _w(s, end + 1).end()
  230. nextchar = s[end:end + 1]
  231. end += 1
  232. if nextchar == ']':
  233. break
  234. elif nextchar != ',':
  235. raise ValueError(errmsg("Expecting ',' delimiter", s, end))
  236. try:
  237. if s[end] in _ws:
  238. end += 1
  239. if s[end] in _ws:
  240. end = _w(s, end + 1).end()
  241. except IndexError:
  242. pass
  243. return values, end
  244. class JSONDecoder(object):
  245. """Simple JSON <http://json.org> decoder
  246. Performs the following translations in decoding by default:
  247. +---------------+-------------------+
  248. | JSON | Python |
  249. +===============+===================+
  250. | object | dict |
  251. +---------------+-------------------+
  252. | array | list |
  253. +---------------+-------------------+
  254. | string | unicode |
  255. +---------------+-------------------+
  256. | number (int) | int, long |
  257. +---------------+-------------------+
  258. | number (real) | float |
  259. +---------------+-------------------+
  260. | true | True |
  261. +---------------+-------------------+
  262. | false | False |
  263. +---------------+-------------------+
  264. | null | None |
  265. +---------------+-------------------+
  266. It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
  267. their corresponding ``float`` values, which is outside the JSON spec.
  268. """
  269. def __init__(self, encoding=None, object_hook=None, parse_float=None,
  270. parse_int=None, parse_constant=None, strict=True,
  271. object_pairs_hook=None):
  272. """``encoding`` determines the encoding used to interpret any ``str``
  273. objects decoded by this instance (utf-8 by default). It has no
  274. effect when decoding ``unicode`` objects.
  275. Note that currently only encodings that are a superset of ASCII work,
  276. strings of other encodings should be passed in as ``unicode``.
  277. ``object_hook``, if specified, will be called with the result
  278. of every JSON object decoded and its return value will be used in
  279. place of the given ``dict``. This can be used to provide custom
  280. deserializations (e.g. to support JSON-RPC class hinting).
  281. ``object_pairs_hook``, if specified will be called with the result of
  282. every JSON object decoded with an ordered list of pairs. The return
  283. value of ``object_pairs_hook`` will be used instead of the ``dict``.
  284. This feature can be used to implement custom decoders that rely on the
  285. order that the key and value pairs are decoded (for example,
  286. collections.OrderedDict will remember the order of insertion). If
  287. ``object_hook`` is also defined, the ``object_pairs_hook`` takes
  288. priority.
  289. ``parse_float``, if specified, will be called with the string
  290. of every JSON float to be decoded. By default this is equivalent to
  291. float(num_str). This can be used to use another datatype or parser
  292. for JSON floats (e.g. decimal.Decimal).
  293. ``parse_int``, if specified, will be called with the string
  294. of every JSON int to be decoded. By default this is equivalent to
  295. int(num_str). This can be used to use another datatype or parser
  296. for JSON integers (e.g. float).
  297. ``parse_constant``, if specified, will be called with one of the
  298. following strings: -Infinity, Infinity, NaN.
  299. This can be used to raise an exception if invalid JSON numbers
  300. are encountered.
  301. If ``strict`` is false (true is the default), then control
  302. characters will be allowed inside strings. Control characters in
  303. this context are those with character codes in the 0-31 range,
  304. including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.
  305. """
  306. self.encoding = encoding
  307. self.object_hook = object_hook
  308. self.object_pairs_hook = object_pairs_hook
  309. self.parse_float = parse_float or float
  310. self.parse_int = parse_int or int
  311. self.parse_constant = parse_constant or _CONSTANTS.__getitem__
  312. self.strict = strict
  313. self.parse_object = JSONObject
  314. self.parse_array = JSONArray
  315. self.parse_string = scanstring
  316. self.scan_once = scanner.make_scanner(self)
  317. def decode(self, s, _w=WHITESPACE.match):
  318. """Return the Python representation of ``s`` (a ``str`` or ``unicode``
  319. instance containing a JSON document)
  320. """
  321. obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  322. end = _w(s, end).end()
  323. if end != len(s):
  324. raise ValueError(errmsg("Extra data", s, end, len(s)))
  325. return obj
  326. def raw_decode(self, s, idx=0):
  327. """Decode a JSON document from ``s`` (a ``str`` or ``unicode``
  328. beginning with a JSON document) and return a 2-tuple of the Python
  329. representation and the index in ``s`` where the document ended.
  330. This can be used to decode a JSON document from a string that may
  331. have extraneous data at the end.
  332. """
  333. try:
  334. obj, end = self.scan_once(s, idx)
  335. except StopIteration:
  336. raise ValueError("No JSON object could be decoded")
  337. return obj, end