json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and 204 Response

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and 204 Response

我一直在尝试在此处搜索此问题的解决方案,但我似乎找不到重复的问题。我有一个天气命令,用户可以在其中按邮政编码或城市进行搜索。城市 URL 在打印 JSON 数据时工作正常,但是当我输入 location 的邮政编码时,它会给我一个 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 错误。我打印出响应代码,它显示为 204 而不是 200,但是当我删除 if location == int(): 语句和另一个 URL 时,打印时没有任何问题邮政编码 JSON 数据。

编辑:将我的代码从 if location == int() 更改为 if location.isdigit() 解决了问题。

if message.content.lower().startswith('!weather'):
    x = message.content.split(" ", 1)
    location = x[1]
    if location == int():
        url = 'https://api.weatherbit.io/v2.0/forecast/daily?postal_code={}&days=1&units=I&key=c85e55e66bfa4cb0ad9c21a3a038d59e'.format(location)
    else:
        url = 'https://api.weatherbit.io/v2.0/forecast/daily?city={}&units=I&key=c85e55e66bfa4cb0ad9c21a3a038d59e'.format(location)
    res = requests.get(url)
    information = res.json()
    print(information)

这是因为代码中的 if 条件 location == int(),它将始终导致 false,因为 int() 将始终为您提供 0,除非预期location value is 0。你可以通过交换城市和邮政编码来检查这个 url.

int()用于获取给定数字或字符串的整数值。在没有任何值的情况下使用它总是 return 0.