1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| def str_to_dict(S): # S 是一个json字符串 dict_result={} if type(S)== str: # S 是字符串 直接处理字符串 S = eval(S) # (字符串转为字典 不传给dict_result(因为字典里面还有其他的数据类型)) print('eval()后的S的值:{},类型是:{}'.format(S,type(S)))
if type (S) == list: # 判断是否是列表,遍历列表里面的内容 for i in S: d = str_to_dict(i) dict_result.update(d)
if type(S)==dict: # 判断是否是字典 for k,v in S.items(): if type(v)==list or type(v)==dict: # 字典里面镶嵌着列表或者字典 d= str_to_dict(v) # (字典里面有列表和字典里面有字典) dict_result.update(d) else: dict_result[k]=v # 单纯是字典,就直接存在dict_result字典中 return dict_result # 返回底层字典 if __name__ == '__main__': J='{"a":"aa","b":[\'{"c":"cc","d":"dd"}\',{"f":{"e":"ee"}}]}' dict = str_to_dict(J) print(dict)
|