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

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

您好,我正在 Python 的文件中使用 JSON:

import json
userData = '''[
{
    "userID" : "20",
    "devices" : {
        "360020000147343433313337" : "V33_03",
        "3f0026001747343438323536" : "Door_03",
        "170035001247343438323536" : "IR_06",
        "28004c000651353530373132" : "BED_17"
    }
},

]'''

info = json.loads(userData)

加载时出现此错误: json.decoder.JSONDecodeError:期望值:

或者有时当我添加一些东西时: json.decoder.JSONDecodeError:期望 属性 名称用双引号引起来:

尝试使用 ast 模块

例如:

import ast
userData = '''[
{
    "userID" : "20",
    "devices" : {
        "360020000147343433313337" : "V33_03",
        "3f0026001747343438323536" : "Door_03",
        "170035001247343438323536" : "IR_06",
        "28004c000651353530373132" : "BED_17"
    }
},
]'''

info = ast.literal_eval(userData)
print(info)

看来格式不对。

userData = '''[
{
    "userID" : "20",
    "devices" : {
        "360020000147343433313337" : "V33_03",
        "3f0026001747343438323536" : "Door_03",
        "170035001247343438323536" : "IR_06",
        "28004c000651353530373132" : "BED_17"
    }
},  <--- remove this ","

]'''

查看我的测试:

>>> import json
>>> json.loads('[{"a":"b"}]')
[{u'a': u'b'}]
>>> json.loads('[{"a":"b"},]')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>>

按原样使用您的示例,无需进一步理解: info = json.loads(json.dumps(userData)) 会起作用。

SO 上有很多关于 python 多行字符串和 JSON 的帖子。理想情况下,您不会从字符串变量加载字符串,那样您将看到一般注释。

通过一些额外的解释,例如数据的来源和格式,我可以提供额外的帮助。

为了将来参考,下面介绍了如何获取 JSON 内容或获取一些垃圾邮件:

import requests


url = 'http://httpbin.org/status/200'
r = requests.get(url)

if 'json' in r.headers.get('Content-Type'):
    js = r.json()
else:
    print('Response content is not in JSON format.')
    js = 'spam'