首页 > 代码库 > python基础:json.loads(str)出现错误总结

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 : {utips: {ucount: 0, uitems: []}}}"  
 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}}  

 

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