Python:json.decoder.JSONDecodeError

时间:2017-07-24 12:08:52

标签: python python-3.x

我想从服务器获取json响应 这是我的代码:

import requests
from requests_ntlm import HttpNtlmAuth

r = requests.get('http://helpbook.com/Home/UserInfo?empId=00458974',
auth=HttpNtlmAuth('domain\\login','password'))
print(r.json())

但每次我收到错误:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\SM\PYTHON_SCRIPTS\Send json query\iso.py", line 6, in <module>
    print(r.json())
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 894, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Program Files\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

如何解决?

1 个答案:

答案 0 :(得分:0)

我没有足够的声誉发表评论。

requests无法解码JSON响应,因为没有JSON响应。您应该首先检查返回代码:

import requests
from requests_ntlm import HttpNtlmAuth

r = requests.get('http://helpbook.com/Home/UserInfo?empId=00458974',
                 auth=HttpNtlmAuth('domain\login', 'password'))

if r.status_code == 200:
    print(r.json())
else:
    print("Request failed: {} - {}".format(r.status_code, r.reason))

你会得到结果: Request failed: 404 - Not Found

使用该信息,您可以调试HTTP API并检查首先收到404错误的原因。