MCPcopy Index your code
hub / github.com/python/cpython / py_scanstring

Function py_scanstring

Lib/json/decoder.py:70–127  ·  view source on GitHub ↗

Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters

(s, end, strict=True,
        _b=BACKSLASH, _m=STRINGCHUNK.match)

Source from the content-addressed store, hash-verified

68 raise JSONDecodeError(msg, s, pos)
69
70def py_scanstring(s, end, strict=True,
71 _b=BACKSLASH, _m=STRINGCHUNK.match):
72 """Scan the string s for a JSON string. End is the index of the
73 character in s after the quote that started the JSON string.
74 Unescapes all valid JSON string escape sequences and raises ValueError
75 on attempt to decode an invalid string. If strict is False then literal
76 control characters are allowed in the string.
77
78 Returns a tuple of the decoded string and the index of the character in s
79 after the end quote."""
80 chunks = []
81 _append = chunks.append
82 begin = end - 1
83 while 1:
84 chunk = _m(s, end)
85 if chunk is None:
86 raise JSONDecodeError("Unterminated string starting at", s, begin)
87 end = chunk.end()
88 content, terminator = chunk.groups()
89 # Content is contains zero or more unescaped string characters
90 if content:
91 _append(content)
92 # Terminator is the end of string, a literal control character,
93 # or a backslash denoting that an escape sequence follows
94 if terminator == '"':
95 break
96 elif terminator != '\\':
97 if strict:
98 #msg = "Invalid control character %r at" % (terminator,)
99 msg = "Invalid control character {0!r} at".format(terminator)
100 raise JSONDecodeError(msg, s, end)
101 else:
102 _append(terminator)
103 continue
104 try:
105 esc = s[end]
106 except IndexError:
107 raise JSONDecodeError("Unterminated string starting at",
108 s, begin) from None
109 # If not a unicode escape sequence, must be in the lookup table
110 if esc != 'u':
111 try:
112 char = _b[esc]
113 except KeyError:
114 msg = "Invalid \\escape: {0!r}".format(esc)
115 raise JSONDecodeError(msg, s, end)
116 end += 1
117 else:
118 uni = _decode_uXXXX(s, end)
119 end += 5
120 if 0xd800 <= uni <= 0xdbff and s[end:end + 2] == '\\u':
121 uni2 = _decode_uXXXX(s, end + 1)
122 if 0xdc00 <= uni2 <= 0xdfff:
123 uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
124 end += 6
125 char = chr(uni)
126 _append(char)
127 return ''.join(chunks), end

Callers

nothing calls this directly

Calls 6

JSONDecodeErrorClass · 0.85
_decode_uXXXXFunction · 0.85
endMethod · 0.45
groupsMethod · 0.45
formatMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…