1 """trivialjson (https://github.com/phihag/trivialjson)"""
6 def raiseError(msg, i):
7 raise ValueError(msg + ' at position ' + str(i) + ' of ' + repr(s) + ': ' + repr(s[i:]))
8 def skipSpace(i, expectMore=True):
9 while i < len(s) and s[i] in ' \t\r\n':
13 raiseError('Premature end', i)
15 def decodeEscape(match):
31 return unichr(int(esc[1:5], 16))
32 if len(esc) == 5+6 and esc[5:7] == '\\u':
33 hi = int(esc[1:5], 16)
34 low = int(esc[7:11], 16)
35 return unichr((hi - 0xd800) * 0x400 + low - 0xdc00 + 0x10000)
36 raise ValueError('Unknown escape ' + str(esc))
43 while s[e-bslashes-1] == '\\':
49 rexp = re.compile(r'\\(u[dD][89aAbB][0-9a-fA-F]{2}\\u[0-9a-fA-F]{4}|u[0-9a-fA-F]{4}|.|$)')
50 stri = rexp.sub(decodeEscape, s[i:e])
56 if s[i] == '}': # Empty dictionary
60 raiseError('Expected a string object key', i)
61 i,key = parseString(i)
63 if i >= len(s) or s[i] != ':':
64 raiseError('Expected a colon', i)
71 raiseError('Expected comma or closing curly brace', i)
76 if s[i] == ']': # Empty array
81 i = skipSpace(i) # Raise exception if premature end
85 raiseError('Expected a comma or closing bracket', i)
88 for k,v in {'true': True, 'false': False, 'null': None}.items():
89 if s.startswith(k, i):
91 raiseError('Not a boolean (or null)', i)
93 mobj = re.match('^(-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][+-]?[0-9]+)?)', s[i:])
95 raiseError('Not a number', i)
97 if '.' in nums or 'e' in nums or 'E' in nums:
98 return (i+len(nums), float(nums))
99 return (i+len(nums), int(nums))
100 CHARMAP = {'{': parseObj, '[': parseArray, '"': parseString, 't': parseDiscrete, 'f': parseDiscrete, 'n': parseDiscrete}
103 i,res = CHARMAP.get(s[i], parseNumber)(i)
104 i = skipSpace(i, False)
108 raise ValueError('Extra data at end of input (index ' + str(i) + ' of ' + repr(s) + ': ' + repr(s[i:]) + ')')