Package cloudfiles :: Module fjson
[frames] | no frames]

Source Code for Module cloudfiles.fjson

 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   
7 -def _loads(string):
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 # look for a real json parser first 31 try: 32 # 2.6 will have a json module in the stdlib 33 from json import loads as json_loads 34 except ImportError: 35 try: 36 # simplejson is popular and pretty good 37 from simplejson import loads as json_loads 38 # fall back on local parser otherwise 39 except ImportError: 40 json_loads = _loads 41 42 __all__ = ['json_loads'] 43