首页 > 解决方案 > Python:请求的 .json() 方法不起作用

问题描述

我制作了这个简单的脚本来测试这个 API

import requests
res = requests.get("https://icanhazdadjoke.com/")
print(res.json())

但我得到了错误:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print(res.json())
  File "/usr/lib/python3/dist-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我用它测试了 API,curl -H "Accept: application/json" https://icanhazdadjoke.com/它返回 OK:

{"id":"JeF69xAQSnb","joke":"A red and a blue ship have just collided in the Caribbean. Apparently the survivors are marooned.","status":200}

我还使用其他 API 进行了测试,但我似乎总是收到此错误。我正在尝试学习如何使用 API,所以我有点迷路了。

标签: jsonapipython-requests

解决方案


推荐阅读