"""Implementation of JSONDecoder"""import refrom json import scannertry:from _json import scanstring as c_scanstringexcept ImportError:c_scanstring = None__all__ = ['JSONDecoder', 'JSONDecodeError']FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALLNaN = float('nan')PosInf = float('inf')NegInf = float('-inf')class JSONDecodeError(ValueError):"""Subclass of ValueError with the following additional properties:msg: The unformatted error messagedoc: The JSON document being parsedpos: The start index of doc where parsing failedlineno: The line corresponding to poscolno: The column corresponding to pos"""# Note that this exception is used from _jsondef __init__(self, msg, doc, pos):lineno = doc.count('\n', 0, pos) + 1colno = pos - doc.rfind('\n', 0, pos)errmsg = '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)ValueError.__init__(self, errmsg)self.msg = msgself.doc = docself.pos = posself.lineno = linenoself.colno = colnodef __reduce__(self):return self.__class__, (self.msg, self.doc, self.pos)_CONSTANTS = {'-Infinity': NegInf,'Infinity': PosInf,'NaN': NaN,}STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)BACKSLASH = {'"': '"', '\\': '\\', '/': '/','b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t',}def _decode_uXXXX(s, pos):esc = s[pos + 1:pos + 5]if len(esc) == 4 and esc[1] not in 'xX':try:return int(esc, 16)except ValueError:passmsg = "Invalid \\uXXXX escape"raise JSONDecodeError(msg, s, pos)def py_scanstring(s, end, strict=True,_b=BACKSLASH, _m=STRINGCHUNK.match):"""Scan the string s for a JSON string. End is the index of thecharacter in s after the quote that started the JSON string.Unescapes all valid JSON string escape sequences and raises ValueErroron attempt to decode an invalid string. If strict is False then literalcontrol characters are allowed in the string.Returns a tuple of the decoded string and the index of the character in safter the end quote."""chunks = []_append = chunks.appendbegin = end - 1while 1:chunk = _m(s, end)if chunk is None:raise JSONDecodeError("Unterminated string starting at", s, begin)end = chunk.end()content, terminator = chunk.groups()# Content is contains zero or more unescaped string charactersif content:_append(content)# Terminator is the end of string, a literal control character,# or a backslash denoting that an escape sequence followsif terminator == '"':breakelif terminator != '\\':if strict:#msg = "Invalid control character %r at" % (terminator,)msg = "Invalid control character {0!r} at".format(terminator)raise JSONDecodeError(msg, s, end)else:_append(terminator)continuetry:esc = s[end]except IndexError:raise JSONDecodeError("Unterminated string starting at",s, begin) from None# If not a unicode escape sequence, must be in the lookup tableif esc != 'u':try:char = _b[esc]except KeyError:msg = "Invalid \\escape: {0!r}".format(esc)raise JSONDecodeError(msg, s, end)end += 1else:uni = _decode_uXXXX(s, end)end += 5if 0xd800 <= uni <= 0xdbff and s[end:end + 2] == '\\u':uni2 = _decode_uXXXX(s, end + 1)if 0xdc00 <= uni2 <= 0xdfff:uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))end += 6char = chr(uni)_append(char)return ''.join(chunks), end# Use speedup if availablescanstring = c_scanstring or py_scanstringWHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)WHITESPACE_STR = ' \t\n\r'def JSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook,memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR):s, end = s_and_endpairs = []pairs_append = pairs.append# Backwards compatibilityif memo is None:memo = {}memo_get = memo.setdefault# Use a slice to prevent IndexError from being raised, the following# check will raise a more specific ValueError if the string is emptynextchar = s[end:end + 1]# Normally we expect nextchar == '"'if nextchar != '"':if nextchar in _ws:end = _w(s, end).end()nextchar = s[end:end + 1]# Trivial empty objectif nextchar == '}':if object_pairs_hook is not None:result = object_pairs_hook(pairs)return result, end + 1pairs = {}if object_hook is not None:pairs = object_hook(pairs)return pairs, end + 1elif nextchar != '"':raise JSONDecodeError("Expecting property name enclosed in double quotes", s, end)end += 1while True:key, end = scanstring(s, end, strict)key = memo_get(key, key)# To skip some function call overhead we optimize the fast paths where# the JSON key separator is ": " or just ":".if s[end:end + 1] != ':':end = _w(s, end).end()if s[end:end + 1] != ':':raise JSONDecodeError("Expecting ':' delimiter", s, end)end += 1try:if s[end] in _ws:end += 1if s[end] in _ws:end = _w(s, end + 1).end()except IndexError:passtry:value, end = scan_once(s, end)except StopIteration as err:raise JSONDecodeError("Expecting value", s, err.value) from Nonepairs_append((key, value))try:nextchar = s[end]if nextchar in _ws:end = _w(s, end + 1).end()nextchar = s[end]except IndexError:nextchar = ''end += 1if nextchar == '}':breakelif nextchar != ',':raise JSONDecodeError("Expecting ',' delimiter", s, end - 1)end = _w(s, end).end()nextchar = s[end:end + 1]end += 1if nextchar != '"':raise JSONDecodeError("Expecting property name enclosed in double quotes", s, end - 1)if object_pairs_hook is not None:result = object_pairs_hook(pairs)return result, endpairs = dict(pairs)if object_hook is not None:pairs = object_hook(pairs)return pairs, enddef JSONArray(s_and_end, scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):s, end = s_and_endvalues = []nextchar = s[end:end + 1]if nextchar in _ws:end = _w(s, end + 1).end()nextchar = s[end:end + 1]# Look-ahead for trivial empty arrayif nextchar == ']':return values, end + 1_append = values.appendwhile True:try:value, end = scan_once(s, end)except StopIteration as err:raise JSONDecodeError("Expecting value", s, err.value) from None_append(value)nextchar = s[end:end + 1]if nextchar in _ws:end = _w(s, end + 1).end()nextchar = s[end:end + 1]end += 1if nextchar == ']':breakelif nextchar != ',':raise JSONDecodeError("Expecting ',' delimiter", s, end - 1)try:if s[end] in _ws:end += 1if s[end] in _ws:end = _w(s, end + 1).end()except IndexError:passreturn values, endclass JSONDecoder(object):"""Simple JSON <http://json.org> decoderPerforms the following translations in decoding by default:+---------------+-------------------+| JSON | Python |+===============+===================+| object | dict |+---------------+-------------------+| array | list |+---------------+-------------------+| string | str |+---------------+-------------------+| number (int) | int |+---------------+-------------------+| number (real) | float |+---------------+-------------------+| true | True |+---------------+-------------------+| false | False |+---------------+-------------------+| null | None |+---------------+-------------------+It also understands ``NaN``, ``Infinity``, and ``-Infinity`` astheir corresponding ``float`` values, which is outside the JSON spec."""def __init__(self, *, object_hook=None, parse_float=None,parse_int=None, parse_constant=None, strict=True,object_pairs_hook=None):"""``object_hook``, if specified, will be called with the resultof every JSON object decoded and its return value will be used inplace of the given ``dict``. This can be used to provide customdeserializations (e.g. to support JSON-RPC class hinting).``object_pairs_hook``, if specified will be called with the result ofevery JSON object decoded with an ordered list of pairs. The returnvalue of ``object_pairs_hook`` will be used instead of the ``dict``.This feature can be used to implement custom decoders.If ``object_hook`` is also defined, the ``object_pairs_hook`` takespriority.``parse_float``, if specified, will be called with the stringof every JSON float to be decoded. By default this is equivalent tofloat(num_str). This can be used to use another datatype or parserfor JSON floats (e.g. decimal.Decimal).``parse_int``, if specified, will be called with the stringof every JSON int to be decoded. By default this is equivalent toint(num_str). This can be used to use another datatype or parserfor JSON integers (e.g. float).``parse_constant``, if specified, will be called with one of thefollowing strings: -Infinity, Infinity, NaN.This can be used to raise an exception if invalid JSON numbersare encountered.If ``strict`` is false (true is the default), then controlcharacters will be allowed inside strings. Control characters inthis context are those with character codes in the 0-31 range,including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``."""self.object_hook = object_hookself.parse_float = parse_float or floatself.parse_int = parse_int or intself.parse_constant = parse_constant or _CONSTANTS.__getitem__self.strict = strictself.object_pairs_hook = object_pairs_hookself.parse_object = JSONObjectself.parse_array = JSONArrayself.parse_string = scanstringself.memo = {}self.scan_once = scanner.make_scanner(self)def decode(self, s, _w=WHITESPACE.match):"""Return the Python representation of ``s`` (a ``str`` instancecontaining a JSON document)."""obj, end = self.raw_decode(s, idx=_w(s, 0).end())end = _w(s, end).end()if end != len(s):raise JSONDecodeError("Extra data", s, end)return objdef raw_decode(self, s, idx=0):"""Decode a JSON document from ``s`` (a ``str`` beginning witha JSON document) and return a 2-tuple of the Pythonrepresentation and the index in ``s`` where the document ended.This can be used to decode a JSON document from a string that mayhave extraneous data at the end."""try:obj, end = self.scan_once(s, idx)except StopIteration as err:raise JSONDecodeError("Expecting value", s, err.value) from Nonereturn obj, end
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。