json.loads 的 Python3 奇怪错误

Sai*_*akR 1 python json flask python-3.x

我在使用服务 api 生成 JSON 响应的 Web 应用程序中使用。该函数的以下部分工作正常并返回 JSON 文本输出:

def get_weather(query = 'london'):
    api_url = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=XXXXX****2a6eaf86760c"
    query = urllib.request.quote(query)
    url = api_url.format(query)
    response = urllib.request.urlopen(url)
    data = response.read()    
    return data
Run Code Online (Sandbox Code Playgroud)

返回的输出是:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":12.95,"pressure":1030,"humidity":68,"temp_min":12.95,"temp_max":12.95,"sea_level":1039.93,"grnd_level":1030},"wind":{"speed":5.11,"deg":279.006},"clouds":{"all":76},"dt":1462290955,"sys":{"message":0.0048,"country":"GB","sunrise":1462249610,"sunset":1462303729},"id":2643743,"name":"London","cod":200}
Run Code Online (Sandbox Code Playgroud)

这意味着这data是一个字符串,不是吗?

但是,评论return data然后添加以下两行:

jsonData = json.loads(data)
return jsonData
Run Code Online (Sandbox Code Playgroud)

产生以下错误:

类型错误:JSON 对象必须是 str,而不是 'bytes'

怎么了?dataJSON 对象,以前作为字符串返回!我需要知道错误在哪里?

Srd*_*bor 5

request库返回的数据是二进制字符串,而json.loads接受strings,因此您需要decode使用请求返回的编码将数据 ( ) 转换为字符串(通常可以假设它是UTF-8)。

您应该能够将代码更改为:

return json.loads(data.decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)

PS:在返回之前存储变量是多余的,所以我简化了事情