json.loads()的字符串中为单引号引发的错误

如下错误属于弱智错误,但是错的原因让我无语,所以记录一下


str2="{'card':6217001650004184441}"
print(json.loads(str2))

Traceback (most recent call last):
File "G:/FastWorkStateServer/logs/redis_fabu.py", line 20, in <module>
print(json.loads(str2))
File "D:\python3.6.5\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "D:\python3.6.5\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\python3.6.5\lib\json\decoder.py", line 355, 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)

 

错误原因:字符串里用单引号来标识字符。

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

import re
test=re.sub('\'','\"',test)
result=json.loads(test)
result['data']
'123'

 

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

c={u"test":124}
d=re.sub("u'","\"",c)  
json.loads(d)

 

posted @ 2018-09-29 16:37  RGC  阅读(2776)  评论(0编辑  收藏  举报