python json json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes

>>> import json
>>> test="{'data':'123'}"
>>> result=json.loads(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "d:\Anaconda3\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "d:\Anaconda3\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "d:\Anaconda3\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=f.read()
>>> c
"{u'meta': {u'code': 200, u'requestId': u'5815f6739fb6b77494061e19'}, u'response
': {u'tips': {u'count': 0, u'items': []}}}"
>>> d=re.sub("u'","\"",c)
>>> d
'{"meta\': {"code\': 200, "requestId\': "5815f6739fb6b77494061e19\'}, "response\
': {"tips\': {"count\': 0, "items\': []}}}'
>>> d=re.sub("'","\"",d)
>>> d
'{"meta": {"code": 200, "requestId": "5815f6739fb6b77494061e19"}, "response": {"
tips": {"count": 0, "items": []}}}'
>>> json.loads(d)
{'response': {'tips': {'items': [], 'count': 0}}, 'meta': {'requestId': '5815f67
39fb6b77494061e19', 'code': 200}}
>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值