blob: b71215b0c17e5c40159e7df5970bfff748768777 [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):
Raymond Hettinger0ad98d82009-04-21 03:09:17 +0000167 pairs = []
168 pairs_append = pairs.append
Christian Heimes90540002008-05-08 14:29:10 +0000169 s = match.string
170 end = _w(s, match.end()).end()
171 nextchar = s[end:end + 1]
172 # Trivial empty object
173 if nextchar == '}':
174 return pairs, end + 1
175 if nextchar != '"':
176 raise ValueError(errmsg("Expecting property name", s, end))
177 end += 1
178 encoding = getattr(context, 'encoding', None)
179 strict = getattr(context, 'strict', True)
180 iterscan = JSONScanner.iterscan
181 while True:
182 key, end = scanstring(s, end, encoding, strict)
183 end = _w(s, end).end()
184 if s[end:end + 1] != ':':
185 raise ValueError(errmsg("Expecting : delimiter", s, end))
186 end = _w(s, end + 1).end()
187 try:
188 value, end = next(iterscan(s, idx=end, context=context))
189 except StopIteration:
190 raise ValueError(errmsg("Expecting object", s, end))
Raymond Hettinger0ad98d82009-04-21 03:09:17 +0000191 pairs_append((key, value))
Christian Heimes90540002008-05-08 14:29:10 +0000192 end = _w(s, end).end()
193 nextchar = s[end:end + 1]
194 end += 1
195 if nextchar == '}':
196 break
197 if nextchar != ',':
198 raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
199 end = _w(s, end).end()
200 nextchar = s[end:end + 1]
201 end += 1
202 if nextchar != '"':
203 raise ValueError(errmsg("Expecting property name", s, end - 1))
Raymond Hettinger0ad98d82009-04-21 03:09:17 +0000204 object_pairs_hook = getattr(context, 'object_pairs_hook', None)
205 if object_pairs_hook is not None:
206 result = object_pairs_hook(pairs)
207 return result, end
208 pairs = dict(pairs)
Christian Heimes90540002008-05-08 14:29:10 +0000209 object_hook = getattr(context, 'object_hook', None)
210 if object_hook is not None:
211 pairs = object_hook(pairs)
212 return pairs, end
213pattern(r'{')(JSONObject)
214
215
216def JSONArray(match, context, _w=WHITESPACE.match):
217 values = []
218 s = match.string
219 end = _w(s, match.end()).end()
220 # Look-ahead for trivial empty array
221 nextchar = s[end:end + 1]
222 if nextchar == ']':
223 return values, end + 1
224 iterscan = JSONScanner.iterscan
225 while True:
226 try:
227 value, end = next(iterscan(s, idx=end, context=context))
228 except StopIteration:
229 raise ValueError(errmsg("Expecting object", s, end))
230 values.append(value)
231 end = _w(s, end).end()
232 nextchar = s[end:end + 1]
233 end += 1
234 if nextchar == ']':
235 break
236 if nextchar != ',':
237 raise ValueError(errmsg("Expecting , delimiter", s, end))
238 end = _w(s, end).end()
239 return values, end
240pattern(r'\[')(JSONArray)
241
242
243ANYTHING = [
244 JSONObject,
245 JSONArray,
246 JSONString,
247 JSONConstant,
248 JSONNumber,
249]
250
251JSONScanner = Scanner(ANYTHING)
252
253
254class JSONDecoder(object):
255 """Simple JSON <http://json.org> decoder
256
257 Performs the following translations in decoding by default:
258
259 +---------------+-------------------+
260 | JSON | Python |
261 +===============+===================+
262 | object | dict |
263 +---------------+-------------------+
264 | array | list |
265 +---------------+-------------------+
266 | string | unicode |
267 +---------------+-------------------+
268 | number (int) | int, long |
269 +---------------+-------------------+
270 | number (real) | float |
271 +---------------+-------------------+
272 | true | True |
273 +---------------+-------------------+
274 | false | False |
275 +---------------+-------------------+
276 | null | None |
277 +---------------+-------------------+
278
279 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
280 their corresponding ``float`` values, which is outside the JSON spec.
281 """
282
283 _scanner = Scanner(ANYTHING)
284 __all__ = ['__init__', 'decode', 'raw_decode']
285
286 def __init__(self, encoding=None, object_hook=None, parse_float=None,
Raymond Hettinger0ad98d82009-04-21 03:09:17 +0000287 parse_int=None, parse_constant=None, strict=True,
288 object_pairs_hook=None):
Christian Heimes90540002008-05-08 14:29:10 +0000289 """``encoding`` determines the encoding used to interpret any ``str``
290 objects decoded by this instance (utf-8 by default). It has no
291 effect when decoding ``unicode`` objects.
292
293 Note that currently only encodings that are a superset of ASCII work,
294 strings of other encodings should be passed in as ``unicode``.
295
296 ``object_hook``, if specified, will be called with the result of
297 every JSON object decoded and its return value will be used in
298 place of the given ``dict``. This can be used to provide custom
299 deserializations (e.g. to support JSON-RPC class hinting).
300
301 ``parse_float``, if specified, will be called with the string
302 of every JSON float to be decoded. By default this is equivalent to
303 float(num_str). This can be used to use another datatype or parser
304 for JSON floats (e.g. decimal.Decimal).
305
306 ``parse_int``, if specified, will be called with the string
307 of every JSON int to be decoded. By default this is equivalent to
308 int(num_str). This can be used to use another datatype or parser
309 for JSON integers (e.g. float).
310
311 ``parse_constant``, if specified, will be called with one of the
312 following strings: -Infinity, Infinity, NaN, null, true, false.
313 This can be used to raise an exception if invalid JSON numbers
314 are encountered.
315
316 """
317 self.encoding = encoding
318 self.object_hook = object_hook
Raymond Hettinger0ad98d82009-04-21 03:09:17 +0000319 self.object_pairs_hook = object_pairs_hook
Christian Heimes90540002008-05-08 14:29:10 +0000320 self.parse_float = parse_float
321 self.parse_int = parse_int
322 self.parse_constant = parse_constant
323 self.strict = strict
324
325 def decode(self, s, _w=WHITESPACE.match):
326 """
327 Return the Python representation of ``s`` (a ``str`` or ``unicode``
328 instance containing a JSON document)
329
330 """
331 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
332 end = _w(s, end).end()
333 if end != len(s):
334 raise ValueError(errmsg("Extra data", s, end, len(s)))
335 return obj
336
337 def raw_decode(self, s, **kw):
338 """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
339 with a JSON document) and return a 2-tuple of the Python
340 representation and the index in ``s`` where the document ended.
341
342 This can be used to decode a JSON document from a string that may
343 have extraneous data at the end.
344
345 """
346 kw.setdefault('context', self)
347 try:
348 obj, end = next(self._scanner.iterscan(s, **kw))
349 except StopIteration:
350 raise ValueError("No JSON object could be decoded")
351 return obj, end