blob: 4e88ba6cc9f2ce5f3f83f456c1e7db08191e0e27 [file] [log] [blame]
Christian Heimes90540002008-05-08 14:29:10 +00001"""Implementation of JSONDecoder
2"""
3
4import re
5import sys
6
7from json.scanner import Scanner, pattern
8try:
9 from _json import scanstring as c_scanstring
10except ImportError:
11 c_scanstring = None
12
13__all__ = ['JSONDecoder']
14
15FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
16
17NaN, PosInf, NegInf = float('nan'), float('inf'), float('-inf')
18
19
20def linecol(doc, pos):
Benjamin Petersona13d4752008-10-16 21:17:24 +000021 if isinstance(doc, bytes):
22 newline = b'\n'
23 else:
24 newline = '\n'
25 lineno = doc.count(newline, 0, pos) + 1
Christian Heimes90540002008-05-08 14:29:10 +000026 if lineno == 1:
27 colno = pos
28 else:
Benjamin Petersona13d4752008-10-16 21:17:24 +000029 colno = pos - doc.rindex(newline, 0, pos)
Christian Heimes90540002008-05-08 14:29:10 +000030 return lineno, colno
31
32
33def errmsg(msg, doc, pos, end=None):
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 endlineno, endcolno = linecol(doc, end)
39 fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
40 return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
41
42
43_CONSTANTS = {
44 '-Infinity': NegInf,
45 'Infinity': PosInf,
46 'NaN': NaN,
47 'true': True,
48 'false': False,
49 'null': None,
50}
51
52
53def JSONConstant(match, context, c=_CONSTANTS):
54 s = match.group(0)
55 fn = getattr(context, 'parse_constant', None)
56 if fn is None:
57 rval = c[s]
58 else:
59 rval = fn(s)
60 return rval, None
61pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant)
62
63
64def JSONNumber(match, context):
65 match = JSONNumber.regex.match(match.string, *match.span())
66 integer, frac, exp = match.groups()
67 if frac or exp:
68 fn = getattr(context, 'parse_float', None) or float
69 res = fn(integer + (frac or '') + (exp or ''))
70 else:
71 fn = getattr(context, 'parse_int', None) or int
72 res = fn(integer)
73 return res, None
Antoine Pitroufd036452008-08-19 17:56:33 +000074pattern(r'(-?(?:0|[1-9][0-9]*))(\.[0-9]+)?([eE][-+]?[0-9]+)?')(JSONNumber)
Christian Heimes90540002008-05-08 14:29:10 +000075
76
77STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
78BACKSLASH = {
79 '"': '"', '\\': '\\', '/': '/',
80 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t',
81}
82
83DEFAULT_ENCODING = "utf-8"
84
85
86def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
87 if encoding is None:
88 encoding = DEFAULT_ENCODING
89 chunks = []
90 _append = chunks.append
91 begin = end - 1
92 while 1:
93 chunk = _m(s, end)
94 if chunk is None:
95 raise ValueError(
96 errmsg("Unterminated string starting at", s, begin))
97 end = chunk.end()
98 content, terminator = chunk.groups()
99 if content:
100 if not isinstance(content, str):
101 content = str(content, encoding)
102 _append(content)
103 if terminator == '"':
104 break
105 elif terminator != '\\':
106 if strict:
107 msg = "Invalid control character {0!r} at".format(terminator)
108 raise ValueError(errmsg(msg, s, end))
109 else:
110 _append(terminator)
111 continue
112 try:
113 esc = s[end]
114 except IndexError:
115 raise ValueError(
116 errmsg("Unterminated string starting at", s, begin))
117 if esc != 'u':
118 try:
119 m = _b[esc]
120 except KeyError:
121 msg = "Invalid \\escape: {0!r}".format(esc)
122 raise ValueError(errmsg(msg, s, end))
123 end += 1
124 else:
125 esc = s[end + 1:end + 5]
126 next_end = end + 5
127 msg = "Invalid \\uXXXX escape"
128 try:
129 if len(esc) != 4:
130 raise ValueError
131 uni = int(esc, 16)
132 if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
133 msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
134 if not s[end + 5:end + 7] == '\\u':
135 raise ValueError
136 esc2 = s[end + 7:end + 11]
137 if len(esc2) != 4:
138 raise ValueError
139 uni2 = int(esc2, 16)
140 uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
141 next_end += 6
142 m = chr(uni)
143 except ValueError:
144 raise ValueError(errmsg(msg, s, end))
145 end = next_end
146 _append(m)
147 return ''.join(chunks), end
148
149
150# Use speedup
151if c_scanstring is not None:
152 scanstring = c_scanstring
153else:
154 scanstring = py_scanstring
155
156def JSONString(match, context):
157 encoding = getattr(context, 'encoding', None)
158 strict = getattr(context, 'strict', True)
159 return scanstring(match.string, match.end(), encoding, strict)
160pattern(r'"')(JSONString)
161
162
163WHITESPACE = re.compile(r'\s*', FLAGS)
164
165
166def JSONObject(match, context, _w=WHITESPACE.match):
167 pairs = {}
168 s = match.string
169 end = _w(s, match.end()).end()
170 nextchar = s[end:end + 1]
171 # Trivial empty object
172 if nextchar == '}':
173 return pairs, end + 1
174 if nextchar != '"':
175 raise ValueError(errmsg("Expecting property name", s, end))
176 end += 1
177 encoding = getattr(context, 'encoding', None)
178 strict = getattr(context, 'strict', True)
179 iterscan = JSONScanner.iterscan
180 while True:
181 key, end = scanstring(s, end, encoding, strict)
182 end = _w(s, end).end()
183 if s[end:end + 1] != ':':
184 raise ValueError(errmsg("Expecting : delimiter", s, end))
185 end = _w(s, end + 1).end()
186 try:
187 value, end = next(iterscan(s, idx=end, context=context))
188 except StopIteration:
189 raise ValueError(errmsg("Expecting object", s, end))
190 pairs[key] = value
191 end = _w(s, end).end()
192 nextchar = s[end:end + 1]
193 end += 1
194 if nextchar == '}':
195 break
196 if nextchar != ',':
197 raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
198 end = _w(s, end).end()
199 nextchar = s[end:end + 1]
200 end += 1
201 if nextchar != '"':
202 raise ValueError(errmsg("Expecting property name", s, end - 1))
203 object_hook = getattr(context, 'object_hook', None)
204 if object_hook is not None:
205 pairs = object_hook(pairs)
206 return pairs, end
207pattern(r'{')(JSONObject)
208
209
210def JSONArray(match, context, _w=WHITESPACE.match):
211 values = []
212 s = match.string
213 end = _w(s, match.end()).end()
214 # Look-ahead for trivial empty array
215 nextchar = s[end:end + 1]
216 if nextchar == ']':
217 return values, end + 1
218 iterscan = JSONScanner.iterscan
219 while True:
220 try:
221 value, end = next(iterscan(s, idx=end, context=context))
222 except StopIteration:
223 raise ValueError(errmsg("Expecting object", s, end))
224 values.append(value)
225 end = _w(s, end).end()
226 nextchar = s[end:end + 1]
227 end += 1
228 if nextchar == ']':
229 break
230 if nextchar != ',':
231 raise ValueError(errmsg("Expecting , delimiter", s, end))
232 end = _w(s, end).end()
233 return values, end
234pattern(r'\[')(JSONArray)
235
236
237ANYTHING = [
238 JSONObject,
239 JSONArray,
240 JSONString,
241 JSONConstant,
242 JSONNumber,
243]
244
245JSONScanner = Scanner(ANYTHING)
246
247
248class JSONDecoder(object):
249 """Simple JSON <http://json.org> decoder
250
251 Performs the following translations in decoding by default:
252
253 +---------------+-------------------+
254 | JSON | Python |
255 +===============+===================+
256 | object | dict |
257 +---------------+-------------------+
258 | array | list |
259 +---------------+-------------------+
260 | string | unicode |
261 +---------------+-------------------+
262 | number (int) | int, long |
263 +---------------+-------------------+
264 | number (real) | float |
265 +---------------+-------------------+
266 | true | True |
267 +---------------+-------------------+
268 | false | False |
269 +---------------+-------------------+
270 | null | None |
271 +---------------+-------------------+
272
273 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
274 their corresponding ``float`` values, which is outside the JSON spec.
275 """
276
277 _scanner = Scanner(ANYTHING)
278 __all__ = ['__init__', 'decode', 'raw_decode']
279
280 def __init__(self, encoding=None, object_hook=None, parse_float=None,
281 parse_int=None, parse_constant=None, strict=True):
282 """``encoding`` determines the encoding used to interpret any ``str``
283 objects decoded by this instance (utf-8 by default). It has no
284 effect when decoding ``unicode`` objects.
285
286 Note that currently only encodings that are a superset of ASCII work,
287 strings of other encodings should be passed in as ``unicode``.
288
289 ``object_hook``, if specified, will be called with the result of
290 every JSON object decoded and its return value will be used in
291 place of the given ``dict``. This can be used to provide custom
292 deserializations (e.g. to support JSON-RPC class hinting).
293
294 ``parse_float``, if specified, will be called with the string
295 of every JSON float to be decoded. By default this is equivalent to
296 float(num_str). This can be used to use another datatype or parser
297 for JSON floats (e.g. decimal.Decimal).
298
299 ``parse_int``, if specified, will be called with the string
300 of every JSON int to be decoded. By default this is equivalent to
301 int(num_str). This can be used to use another datatype or parser
302 for JSON integers (e.g. float).
303
304 ``parse_constant``, if specified, will be called with one of the
305 following strings: -Infinity, Infinity, NaN, null, true, false.
306 This can be used to raise an exception if invalid JSON numbers
307 are encountered.
308
309 """
310 self.encoding = encoding
311 self.object_hook = object_hook
312 self.parse_float = parse_float
313 self.parse_int = parse_int
314 self.parse_constant = parse_constant
315 self.strict = strict
316
317 def decode(self, s, _w=WHITESPACE.match):
318 """
319 Return the Python representation of ``s`` (a ``str`` or ``unicode``
320 instance containing a JSON document)
321
322 """
323 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
324 end = _w(s, end).end()
325 if end != len(s):
326 raise ValueError(errmsg("Extra data", s, end, len(s)))
327 return obj
328
329 def raw_decode(self, s, **kw):
330 """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
331 with a JSON document) and return a 2-tuple of the Python
332 representation and the index in ``s`` where the document ended.
333
334 This can be used to decode a JSON document from a string that may
335 have extraneous data at the end.
336
337 """
338 kw.setdefault('context', self)
339 try:
340 obj, end = next(self._scanner.iterscan(s, **kw))
341 except StopIteration:
342 raise ValueError("No JSON object could be decoded")
343 return obj, end