You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用requests调用Numbers API时JSONDecodeError报错求助

解决Numbers API的JSON解析错误问题

问题出在Numbers API的默认响应格式是纯文本,而非JSON。你需要明确告知API返回JSON格式的响应,以下是三种可行方法:

方法1:在URL末尾添加/json后缀

直接修改请求URL,触发API返回JSON格式:

import requests

resp_random_1_100_int = requests.get(
    "http://numbersapi.com/random/json",
    params={
        "min": "0",
        "max": "100"
    }
)

# 现在可正常解析JSON
data = resp_random_1_100_int.json()
print(data["text"])
print(data["number"])
print(data["type"])

方法2:添加json=true请求参数

在参数中指定返回JSON格式:

import requests

resp_random_1_100_int = requests.get(
    "http://numbersapi.com/random",
    params={
        "min": "0",
        "max": "100",
        "json": "true"
    }
)

data = resp_random_1_100_int.json()
print(data["text"])
print(data["number"])
print(data["type"])

方法3:设置Accept请求头

通过请求头声明期望JSON格式的响应:

import requests

headers = {'Accept': 'application/json'}
resp_random_1_100_int = requests.get(
    "http://numbersapi.com/random",
    params={"min": "0", "max": "100"},
    headers=headers
)

data = resp_random_1_100_int.json()
print(data["text"])
print(data["number"])
print(data["type"])

补充说明

你之前设置的Content-type请求头作用是告知服务器你发送的请求体格式,但这里需要的是让服务器返回JSON,因此应该用Accept头声明期望的响应格式。不过Numbers API对URL后缀和参数的支持更直接,优先推荐前两种方法。

内容的提问来源于stack exchange,提问作者Cflux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:30:42