python字符串转字典

方法一

  • 最常见的一种,使用json进行转换
import json
s = {"name": "张三"}
print(json.loads(s))
------

{'name': '张三'}
  • 但是这种方式有可能会出现问题,例如单引号的情况
s = "{'name': '张三'}"
print(json.loads(s))
------

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

方法二

  • 使用eval
s = "{'name': '张三'}"
print(eval(s))
------

{'name': '张三'}

方法三

  • 使用ast.literal_eval
import ast
s = "{'name': '张三'}"
print(ast.literal_eval(s))
------

{'name': '张三'}

  参考链接:时光不写博客-python字符串转字典