Python字符串转换成字典

方法1:

--案例1

headers字符串{}中是双引号,外面是单引号,能正常转换成dict字典格式

1
2
3
4
5
import json
headers = '{"Content-Type": "application/json"}'
headers = json.loads(headers)
print(headers)
print(type(headers))

响应结果:

{'Content-Type': 'application/json'}
<class 'dict'>

--案例2字符串{}中是单引号,外面是双引号,转换失败报错

1
2
3
4
5
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 却存在安全性的问题

1
2
3
4
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

1
2
3
4
5
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/

 

posted @   chloe_qq  阅读(253)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示