与json.loads的Python3奇怪错误[重复]

时间:2022-02-17 06:40:18

This question already has an answer here:

这个问题在这里已有答案:

I'm using in a web application that uses service api generates JSON response. The following part of the function works fine and returns JSON text output:

我在使用服务api的Web应用程序中使用flask生成JSON响应。该函数的以下部分工作正常并返回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

The output returned is:

返回的输出是:

{"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}

This mean that data is a string, does not it?

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

However, commenting the return data and then adding the following two lines:

但是,注释返回数据然后添加以下两行:

jsonData = json.loads(data)
return jsonData

generates the following error:

生成以下错误:

TypeError: the JSON object must be str, not 'bytes'

TypeError:JSON对象必须是str,而不是'bytes'

What's wrong? data, the JSON object, previously returned as a string! I need to know where is the mistake?

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

1 个解决方案

#1


2  

The data returned by request library is a binary string while json.loads accepts strings so you need to convert the data (decode) to a string using the encoding that your request returns (which is usually ok to assume that it is UTF-8).

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

You should be able to just change your code to this:

您应该只需将代码更改为:

return json.loads(data.decode("utf-8"))

PS: Storing the variable right before returning it is redundant so I simplified things

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

#1


2  

The data returned by request library is a binary string while json.loads accepts strings so you need to convert the data (decode) to a string using the encoding that your request returns (which is usually ok to assume that it is UTF-8).

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

You should be able to just change your code to this:

您应该只需将代码更改为:

return json.loads(data.decode("utf-8"))

PS: Storing the variable right before returning it is redundant so I simplified things

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