0001"""
0002Implementation of JSONDecoder
0003"""
0004import re
0005import sys
0006
0007from simplejson.scanner import Scanner, pattern
0008try:
0009 from simplejson import _speedups
0010except:
0011 _speedups = None
0012
0013FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
0014
0015def _floatconstants():
0016 import struct
0017 import sys
0018 _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
0019 if sys.byteorder != 'big':
0020 _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
0021 nan, inf = struct.unpack('dd', _BYTES)
0022 return nan, inf, -inf
0023
0024NaN, PosInf, NegInf = _floatconstants()
0025
0026def linecol(doc, pos):
0027 lineno = doc.count('\n', 0, pos) + 1
0028 if lineno == 1:
0029 colno = pos
0030 else:
0031 colno = pos - doc.rindex('\n', 0, pos)
0032 return lineno, colno
0033
0034def errmsg(msg, doc, pos, end=None):
0035 lineno, colno = linecol(doc, pos)
0036 if end is None:
0037 return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)
0038 endlineno, endcolno = linecol(doc, end)
0039 return '%s: line %d column %d - line %d column %d (char %d - %d)' % (
0040 msg, lineno, colno, endlineno, endcolno, pos, end)
0041
0042_CONSTANTS = {
0043 '-Infinity': NegInf,
0044 'Infinity': PosInf,
0045 'NaN': NaN,
0046 'true': True,
0047 'false': False,
0048 'null': None,
0049}
0050
0051def JSONConstant(match, context, c=_CONSTANTS):
0052 s = match.group(0)
0053 fn = getattr(context, 'parse_constant', None)
0054 if fn is None:
0055 rval = c[s]
0056 else:
0057 rval = fn(s)
0058 return rval, None
0059pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant)
0060
0061def JSONNumber(match, context):
0062 match = JSONNumber.regex.match(match.string, *match.span())
0063 integer, frac, exp = match.groups()
0064 if frac or exp:
0065 fn = getattr(context, 'parse_float', None) or float
0066 res = fn(integer + (frac or '') + (exp or ''))
0067 else:
0068 fn = getattr(context, 'parse_int', None) or int
0069 res = fn(integer)
0070 return res, None
0071pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber)
0072
0073STRINGCHUNK = re.compile(r'(.*?)(["\\])', FLAGS)
0074BACKSLASH = {
0075 '"': u'"', '\\': u'\\', '/': u'/',
0076 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
0077}
0078
0079DEFAULT_ENCODING = "utf-8"
0080
0081def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match):
0082 if encoding is None:
0083 encoding = DEFAULT_ENCODING
0084 chunks = []
0085 _append = chunks.append
0086 begin = end - 1
0087 while 1:
0088 chunk = _m(s, end)
0089 if chunk is None:
0090 raise ValueError(
0091 errmsg("Unterminated string starting at", s, begin))
0092 end = chunk.end()
0093 content, terminator = chunk.groups()
0094 if content:
0095 if not isinstance(content, unicode):
0096 content = unicode(content, encoding)
0097 _append(content)
0098 if terminator == '"':
0099 break
0100 try:
0101 esc = s[end]
0102 except IndexError:
0103 raise ValueError(
0104 errmsg("Unterminated string starting at", s, begin))
0105 if esc != 'u':
0106 try:
0107 m = _b[esc]
0108 except KeyError:
0109 raise ValueError(
0110 errmsg("Invalid \\escape: %r" % (esc,), s, end))
0111 end += 1
0112 else:
0113 esc = s[end + 1:end + 5]
0114 next_end = end + 5
0115 msg = "Invalid \\uXXXX escape"
0116 try:
0117 if len(esc) != 4:
0118 raise ValueError
0119 uni = int(esc, 16)
0120 if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
0121 msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
0122 if not s[end + 5:end + 7] == '\\u':
0123 raise ValueError
0124 esc2 = s[end + 7:end + 11]
0125 if len(esc2) != 4:
0126 raise ValueError
0127 uni2 = int(esc2, 16)
0128 uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
0129 next_end += 6
0130 m = unichr(uni)
0131 except ValueError:
0132 raise ValueError(errmsg(msg, s, end))
0133 end = next_end
0134 _append(m)
0135 return u''.join(chunks), end
0136
0137
0138if _speedups is not None:
0139 scanstring = _speedups.scanstring
0140
0141def JSONString(match, context):
0142 encoding = getattr(context, 'encoding', None)
0143 return scanstring(match.string, match.end(), encoding)
0144pattern(r'"')(JSONString)
0145
0146WHITESPACE = re.compile(r'\s*', FLAGS)
0147
0148def JSONObject(match, context, _w=WHITESPACE.match):
0149 pairs = {}
0150 s = match.string
0151 end = _w(s, match.end()).end()
0152 nextchar = s[end:end + 1]
0153
0154 if nextchar == '}':
0155 return pairs, end + 1
0156 if nextchar != '"':
0157 raise ValueError(errmsg("Expecting property name", s, end))
0158 end += 1
0159 encoding = getattr(context, 'encoding', None)
0160 iterscan = JSONScanner.iterscan
0161 while True:
0162 key, end = scanstring(s, end, encoding)
0163 end = _w(s, end).end()
0164 if s[end:end + 1] != ':':
0165 raise ValueError(errmsg("Expecting : delimiter", s, end))
0166 end = _w(s, end + 1).end()
0167 try:
0168 value, end = iterscan(s, idx=end, context=context).next()
0169 except StopIteration:
0170 raise ValueError(errmsg("Expecting object", s, end))
0171 pairs[key] = value
0172 end = _w(s, end).end()
0173 nextchar = s[end:end + 1]
0174 end += 1
0175 if nextchar == '}':
0176 break
0177 if nextchar != ',':
0178 raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
0179 end = _w(s, end).end()
0180 nextchar = s[end:end + 1]
0181 end += 1
0182 if nextchar != '"':
0183 raise ValueError(errmsg("Expecting property name", s, end - 1))
0184 object_hook = getattr(context, 'object_hook', None)
0185 if object_hook is not None:
0186 pairs = object_hook(pairs)
0187 return pairs, end
0188pattern(r'{')(JSONObject)
0189
0190def JSONArray(match, context, _w=WHITESPACE.match):
0191 values = []
0192 s = match.string
0193 end = _w(s, match.end()).end()
0194
0195 nextchar = s[end:end + 1]
0196 if nextchar == ']':
0197 return values, end + 1
0198 iterscan = JSONScanner.iterscan
0199 while True:
0200 try:
0201 value, end = iterscan(s, idx=end, context=context).next()
0202 except StopIteration:
0203 raise ValueError(errmsg("Expecting object", s, end))
0204 values.append(value)
0205 end = _w(s, end).end()
0206 nextchar = s[end:end + 1]
0207 end += 1
0208 if nextchar == ']':
0209 break
0210 if nextchar != ',':
0211 raise ValueError(errmsg("Expecting , delimiter", s, end))
0212 end = _w(s, end).end()
0213 return values, end
0214pattern(r'\[')(JSONArray)
0215
0216ANYTHING = [
0217 JSONObject,
0218 JSONArray,
0219 JSONString,
0220 JSONConstant,
0221 JSONNumber,
0222]
0223
0224JSONScanner = Scanner(ANYTHING)
0225
0226class JSONDecoder(object):
0227 """
0228 Simple JSON <http://json.org> decoder
0229
0230 Performs the following translations in decoding by default:
0231
0232 +---------------+-------------------+
0233 | JSON | Python |
0234 +===============+===================+
0235 | object | dict |
0236 +---------------+-------------------+
0237 | array | list |
0238 +---------------+-------------------+
0239 | string | unicode |
0240 +---------------+-------------------+
0241 | number (int) | int, long |
0242 +---------------+-------------------+
0243 | number (real) | float |
0244 +---------------+-------------------+
0245 | true | True |
0246 +---------------+-------------------+
0247 | false | False |
0248 +---------------+-------------------+
0249 | null | None |
0250 +---------------+-------------------+
0251
0252 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
0253 their corresponding ``float`` values, which is outside the JSON spec.
0254 """
0255
0256 _scanner = Scanner(ANYTHING)
0257 __all__ = ['__init__', 'decode', 'raw_decode']
0258
0259 def __init__(self, encoding=None, object_hook=None, parse_float=None,
0260 parse_int=None, parse_constant=None):
0261 """
0262 ``encoding`` determines the encoding used to interpret any ``str``
0263 objects decoded by this instance (utf-8 by default). It has no
0264 effect when decoding ``unicode`` objects.
0265
0266 Note that currently only encodings that are a superset of ASCII work,
0267 strings of other encodings should be passed in as ``unicode``.
0268
0269 ``object_hook``, if specified, will be called with the result
0270 of every JSON object decoded and its return value will be used in
0271 place of the given ``dict``. This can be used to provide custom
0272 deserializations (e.g. to support JSON-RPC class hinting).
0273
0274 ``parse_float``, if specified, will be called with the string
0275 of every JSON float to be decoded. By default this is equivalent to
0276 float(num_str). This can be used to use another datatype or parser
0277 for JSON floats (e.g. decimal.Decimal).
0278
0279 ``parse_int``, if specified, will be called with the string
0280 of every JSON int to be decoded. By default this is equivalent to
0281 int(num_str). This can be used to use another datatype or parser
0282 for JSON integers (e.g. float).
0283
0284 ``parse_constant``, if specified, will be called with one of the
0285 following strings: -Infinity, Infinity, NaN, null, true, false.
0286 This can be used to raise an exception if invalid JSON numbers
0287 are encountered.
0288 """
0289 self.encoding = encoding
0290 self.object_hook = object_hook
0291 self.parse_float = parse_float
0292 self.parse_int = parse_int
0293 self.parse_constant = parse_constant
0294
0295 def decode(self, s, _w=WHITESPACE.match):
0296 """
0297 Return the Python representation of ``s`` (a ``str`` or ``unicode``
0298 instance containing a JSON document)
0299 """
0300 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
0301 end = _w(s, end).end()
0302 if end != len(s):
0303 raise ValueError(errmsg("Extra data", s, end, len(s)))
0304 return obj
0305
0306 def raw_decode(self, s, **kw):
0307 """
0308 Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
0309 with a JSON document) and return a 2-tuple of the Python
0310 representation and the index in ``s`` where the document ended.
0311
0312 This can be used to decode a JSON document from a string that may
0313 have extraneous data at the end.
0314 """
0315 kw.setdefault('context', self)
0316 try:
0317 obj, end = self._scanner.iterscan(s, **kw).next()
0318 except StopIteration:
0319 raise ValueError("No JSON object could be decoded")
0320 return obj, end
0321
0322__all__ = ['JSONDecoder']