python使用json将字符串转字典报错的解决
作者:Lion King
问题描述
C:\Users\lenovo\AppData\Local\Programs\Python\Python37\python.exe D:/360MoveData/Users/lenovo/Desktop/startProject/OAS.Cloud.PAAS_Interface/TestCases/UM/Test_01_register.py
D:\360MoveData\Users\lenovo\Desktop\startProject\OAS.Cloud.PAAS_Interface\common\CaseData.ini
Traceback (most recent call last):
File "D:/360MoveData/Users/lenovo/Desktop/startProject/OAS.Cloud.PAAS_Interface/TestCases/UM/Test_01_register.py", line 73, in <module>
Test_UM_register().test_01()
File "D:/360MoveData/Users/lenovo/Desktop/startProject/OAS.Cloud.PAAS_Interface/TestCases/UM/Test_01_register.py", line 52, in test_01
headers = json.loads(dataList[1])
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\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
如上,json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes
意思为jsondecodeerror:期望属性名用双引号括起来
问题分析
我查看我的原始数据,格式为:
{‘Content-Type': ‘application/json'}
python对单引号、双引号都认为是引号,但对于json来说,它识别是按照双引号来的。因此,凡是用json来格式转换,必定将单引号转为双引号,必要的时候加“\”转义。
通过上述问题分析,我们得到两个解决方案:
- 将原格式换成双引号;
- 换其它方式来转换
问题解决
1、将原格式换成双引号
{‘Content-Type': ‘application/json'}
改为
{“Content-Type”: “application/json”}
验证结果:
成功
2、换其它方式来转换
headers = eval(dataList[1]) # headers = json.loads(dataList[1])
验证结果:
成功
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。