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 "", line 1, in 
  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}}
>>>

你可能感兴趣的:(python,json,python)