python基础:json.loads(str)出现错误总结

 1 >>> import json  
 2 >>> test="{'data':'123'}"  
 3 >>> result=json.loads(test)  
 4 Traceback (most recent call last):  
 5   File "<stdin>", line 1, in <module>  
 6   File "d:\Anaconda3\lib\json\__init__.py", line 319, in loads  
 7     return _default_decoder.decode(s)  
 8   File "d:\Anaconda3\lib\json\decoder.py", line 339, in decode  
 9     obj, end = self.raw_decode(s, idx=_w(s, 0).end())  
10   File "d:\Anaconda3\lib\json\decoder.py", line 355, in raw_decode  
11     obj, end = self.scan_once(s, idx)  
12 json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes:  
13  line 1 column 2 (char 1)

原因在于:字符串里用单引号来标识字符。

解决办法如下:将字符串里的单引号替换成双引号

 

1 >>> import re  
2 >>> test=re.sub('\'','\"',test)  
3 >>> result=json.loads(test)  
4 >>> result['data']  
5 '123'  

 

对于带u'的字符串,u也要去掉:

 1 >>> c=f.read()  
 2 >>> c  
 3 "{u'meta': {u'code': 200, u'requestId': u'5815f6739fb6b77494061e19'}, u'response  
 4 ': {u'tips': {u'count': 0, u'items': []}}}"  
 5 >>> d=re.sub("u'","\"",c)  
 6 >>> d  
 7 '{"meta\': {"code\': 200, "requestId\': "5815f6739fb6b77494061e19\'}, "response\  
 8 ': {"tips\': {"count\': 0, "items\': []}}}'  
 9 >>> d=re.sub("'","\"",d)  
10 >>> d  
11 '{"meta": {"code": 200, "requestId": "5815f6739fb6b77494061e19"}, "response": {"  
12 tips": {"count": 0, "items": []}}}'  
13 >>> json.loads(d)  
14 {'response': {'tips': {'items': [], 'count': 0}}, 'meta': {'requestId': '5815f67  
15 39fb6b77494061e19', 'code': 200}}  

 

转载于:https://www.cnblogs.com/yizhenfeng168/p/6984897.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值