1 from tokenize import generate_tokens, STRING, NAME, OP
2 from cStringIO import StringIO
3 from re import compile, DOTALL
4
5 comments = compile(r'/\*.*\*/|//[^\r\n]*', DOTALL)
6
8 '''
9 Fairly competent json parser exploiting the python tokenizer and eval()
10
11 _loads(serialized_json) -> object
12 '''
13 try:
14 res = []
15 consts = {'true': True, 'false': False, 'null': None}
16 string = '(' + comments.sub('', string) + ')'
17 for type, val, _, _, _ in generate_tokens(StringIO(string).readline):
18 if (type == OP and val not in '[]{}:,()-') or \
19 (type == NAME and val not in consts):
20 raise AttributeError()
21 elif type == STRING:
22 res.append('u')
23 res.append(val.replace('\\/', '/'))
24 else:
25 res.append(val)
26 return eval(''.join(res), {}, consts)
27 except:
28 raise AttributeError()
29
30
31 try:
32
33 from json import loads as json_loads
34 except ImportError:
35 try:
36
37 from simplejson import loads as json_loads
38
39 except ImportError:
40 json_loads = _loads
41
42 __all__ = ['json_loads']
43