通过ast模块处理
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<br />import ast str_info = '{"name": "nock", "age": 18}' dict_info = ast.literal_eval(str_info) print("string info type is -->: %s" % (type(str_info))) print("dict info type is -->: %s" % (type(dict_info))) s_info = "{'name': 'nock', 'age': 18}" d_info = ast.literal_eval(s_info) print("s info type is -->: %s" % (type(s_info))) print("d info type is -->: %s" % (type(d_info))) |
Result:
1 2 3 4 5 |
string info type is -->: <class 'str'> dict info type is -->: <class 'dict'> s info type is -->: <class 'str'> d info type is -->: <class 'dict'> |
使用ast.literal_eval进行转换既不存在使用json 模块进行转换的问题,也不存在使用eval模块进行转换的安全性问题,因此推荐大家使用ast.literal_eval的方法。
