Python字符串转换成字典
方法1:
--案例1
headers字符串{}中是双引号,外面是单引号,能正常转换成dict字典格式
import json
headers = '{"Content-Type": "application/json"}'
headers = json.loads(headers)
print(headers)
print(type(headers))
响应结果:
{'Content-Type': 'application/json'}
<class 'dict'>
--案例2字符串{}中是单引号,外面是双引号,转换失败报错
import json
headers = "{'Content-Type': 'application/json'}"
headers = json.loads(headers)
print(headers)
print(type(headers))
响应结果:
Traceback (most recent call last):
File "G:/Django项目/pythonProject/Python_json/Demo01_json.py", line 3, in <module>
headers = json.loads(headers)
File "C:\Users\huangyanqiu\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\huangyanqiu\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\huangyanqiu\AppData\Local\Programs\Python\Python38\lib\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)
Process finished with exit code 1
方法2
eval函数将字符字典,通过 eval 进行转换就不存在上面使用 json 进行转换的问题。但是,使用 eval 却存在安全性的问题
headers = "{'Content-Type': 'application/json'}"
headers = eval(headers)
print(headers)
print(type(headers))
响应结果:
{'Content-Type': 'application/json'}
<class 'dict'>
方法3
使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval
import ast
headers = "{'Content-Type': 'application/json'}"
headers = ast.literal_eval(headers)
print(headers)
print(type(headers))
响应结果:
{'Content-Type': 'application/json'}
<class 'dict'>
原文地址:http://ww7.funhacks.net/

浙公网安备 33010602011771号