blob: acaee251f36f0ba8441321df256773e8c6298c32 [file] [log] [blame]
Brett Cannon4b964f92008-05-05 20:21:38 +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
17
18def _floatconstants():
19 import struct
20 import sys
21 _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
22 if sys.byteorder != 'big':
23 _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
24 nan, inf = struct.unpack('dd', _BYTES)
25 return nan, inf, -inf
26
27NaN, PosInf, NegInf = _floatconstants()
28
29
30def linecol(doc, pos):
31 lineno = doc.count('\n', 0, pos) + 1
32 if lineno == 1:
33 colno = pos
34 else:
35 colno = pos - doc.rindex('\n', 0, pos)
36 return lineno, colno
37
38
39def errmsg(msg, doc, pos, end=None):
40 lineno, colno = linecol(doc, pos)
41 if end is None:
42 fmt = '{0}: line {1} column {2} (char {3})'
43 return fmt.format(msg, lineno, colno, pos)
44 endlineno, endcolno = linecol(doc, end)
45 fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
46 return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
47
48
49_CONSTANTS = {
50 '-Infinity': NegInf,
51 'Infinity': PosInf,
52 'NaN': NaN,
53 'true': True,
54 'false': False,
55 'null': None,
56}
57
58
59def JSONConstant(match, context, c=_CONSTANTS):
60 s = match.group(0)
61 fn = getattr(context, 'parse_constant', None)
62 if fn is None:
63 rval = c[s]
64 else:
65 rval = fn(s)
66 return rval, None
67pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant)
68
69
70def JSONNumber(match, context):
71 match = JSONNumber.regex.match(match.string, *match.span())
72 integer, frac, exp = match.groups()
73 if frac or exp:
74 fn = getattr(context, 'parse_float', None) or float
75 res = fn(integer + (frac or '') + (exp or ''))
76 else:
77 fn = getattr(context, 'parse_int', None) or int
78 res = fn(integer)
79 return res, None
80pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber)
81
82
83STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
84BACKSLASH = {
85 '"': u'"', '\\': u'\\', '/': u'/',
86 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
87}
88
89DEFAULT_ENCODING = "utf-8"
90
91
92def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
93 if encoding is None:
94 encoding = DEFAULT_ENCODING
95 chunks = []
96 _append = chunks.append
97 begin = end - 1
98 while 1:
99 chunk = _m(s, end)
100 if chunk is None:
101 raise ValueError(
102 errmsg("Unterminated string starting at", s, begin))
103 end = chunk.end()
104 content, terminator = chunk.groups()
105 if content:
106 if not isinstance(content, unicode):
107 content = unicode(content, encoding)
108 _append(content)
109 if terminator == '"':
110 break
111 elif terminator != '\\':
112 if strict:
113 msg = "Invalid control character {0!r} at".format(terminator)
114 raise ValueError(errmsg(msg, s, end))
115 else:
116 _append(terminator)
117 continue
118 try:
119 esc = s[end]
120 except IndexError:
121 raise ValueError(
122 errmsg("Unterminated string starting at", s, begin))
123 if esc != 'u':
124 try:
125 m = _b[esc]
126 except KeyError:
127 msg = "Invalid \\escape: {0!r}".format(esc)
128 raise ValueError(errmsg(msg, s, end))
129 end += 1
130 else:
131 esc = s[end + 1:end + 5]
132 next_end = end + 5
133 msg = "Invalid \\uXXXX escape"
134 try:
135 if len(esc) != 4:
136 raise ValueError
137 uni = int(esc, 16)
138 if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
139 msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
140 if not s[end + 5:end + 7] == '\\u':
141 raise ValueError
142 esc2 = s[end + 7:end + 11]
143 if len(esc2) != 4:
144 raise ValueError
145 uni2 = int(esc2, 16)
146 uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
147 next_end += 6
148 m = unichr(uni)
149 except ValueError:
150 raise ValueError(errmsg(msg, s, end))
151 end = next_end
152 _append(m)
153 return u''.join(chunks), end
154
155
156# Use speedup
157if c_scanstring is not None:
158 scanstring = c_scanstring
159else:
160 scanstring = py_scanstring
161
162def JSONString(match, context):
163 encoding = getattr(context, 'encoding', None)
164 strict = getattr(context, 'strict', True)
165 return scanstring(match.string, match.end(), encoding, strict)
166pattern(r'"')(JSONString)
167
168
169WHITESPACE = re.compile(r'\s*', FLAGS)
170
171
172def JSONObject(match, context, _w=WHITESPACE.match):
173 pairs = {}
174 s = match.string
175 end = _w(s, match.end()).end()
176 nextchar = s[end:end + 1]
177 # Trivial empty object
178 if nextchar == '}':
179 return pairs, end + 1
180 if nextchar != '"':
181 raise ValueError(errmsg("Expecting property name", s, end))
182 end += 1
183 encoding = getattr(context, 'encoding', None)
184 strict = getattr(context, 'strict', True)
185 iterscan = JSONScanner.iterscan
186 while True:
187 key, end = scanstring(s, end, encoding, strict)
188 end = _w(s, end).end()
189 if s[end:end + 1] != ':':
190 raise ValueError(errmsg("Expecting : delimiter", s, end))
191 end = _w(s, end + 1).end()
192 try:
193 value, end = iterscan(s, idx=end, context=context).next()
194 except StopIteration:
195 raise ValueError(errmsg("Expecting object", s, end))
196 pairs[key] = value
197 end = _w(s, end).end()
198 nextchar = s[end:end + 1]
199 end += 1
200 if nextchar == '}':
201 break
202 if nextchar != ',':
203 raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
204 end = _w(s, end).end()
205 nextchar = s[end:end + 1]
206 end += 1
207 if nextchar != '"':
208 raise ValueError(errmsg("Expecting property name", s, end - 1))
209 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 = iterscan(s, idx=end, context=context).next()
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,
287 parse_int=None, parse_constant=None, strict=True):
288 """``encoding`` determines the encoding used to interpret any ``str``
289 objects decoded by this instance (utf-8 by default). It has no
290 effect when decoding ``unicode`` objects.
291
292 Note that currently only encodings that are a superset of ASCII work,
293 strings of other encodings should be passed in as ``unicode``.
294
295 ``object_hook``, if specified, will be called with the result of
296 every JSON object decoded and its return value will be used in
297 place of the given ``dict``. This can be used to provide custom
298 deserializations (e.g. to support JSON-RPC class hinting).
299
300 ``parse_float``, if specified, will be called with the string
301 of every JSON float to be decoded. By default this is equivalent to
302 float(num_str). This can be used to use another datatype or parser
303 for JSON floats (e.g. decimal.Decimal).
304
305 ``parse_int``, if specified, will be called with the string
306 of every JSON int to be decoded. By default this is equivalent to
307 int(num_str). This can be used to use another datatype or parser
308 for JSON integers (e.g. float).
309
310 ``parse_constant``, if specified, will be called with one of the
311 following strings: -Infinity, Infinity, NaN, null, true, false.
312 This can be used to raise an exception if invalid JSON numbers
313 are encountered.
314
315 """
316 self.encoding = encoding
317 self.object_hook = object_hook
318 self.parse_float = parse_float
319 self.parse_int = parse_int
320 self.parse_constant = parse_constant
321 self.strict = strict
322
323 def decode(self, s, _w=WHITESPACE.match):
324 """
325 Return the Python representation of ``s`` (a ``str`` or ``unicode``
326 instance containing a JSON document)
327
328 """
329 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
330 end = _w(s, end).end()
331 if end != len(s):
332 raise ValueError(errmsg("Extra data", s, end, len(s)))
333 return obj
334
335 def raw_decode(self, s, **kw):
336 """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
337 with a JSON document) and return a 2-tuple of the Python
338 representation and the index in ``s`` where the document ended.
339
340 This can be used to decode a JSON document from a string that may
341 have extraneous data at the end.
342
343 """
344 kw.setdefault('context', self)
345 try:
346 obj, end = self._scanner.iterscan(s, **kw).next()
347 except StopIteration:
348 raise ValueError("No JSON object could be decoded")
349 return obj, end