Warm tip: This article is reproduced from serverfault.com, please click

python-将字符串的一部分分配给自己的变量

(python - Assigning parts of a string to their own variables)

发布于 2020-11-28 23:30:26

我一直在使用天气API,希望将返回的API数据中的值分配给某些变量。例如,我想分配lonlattemp,并humidity在下面在我的Python代码自己的变量API的数据值,所以下面是我的结果:

lon = -87.74
lat = 41.9
temp = 46.49
humidity = 61

这是我从API请求中收到的数据:

b'{"coord":{"lon":-87.74,"lat":41.9},"weather": 
[{"id":800,"main":"Clear","description":"clear 
sky","icon":"01n"}],"base":"stations","main": 
{"temp":46.49,"feels_like":35.37,"temp_min":45,"temp_max":48.2,"pressure":1018,"humidity":61},"visibility":10000,"wind":{"speed":13.87,"deg":210,"gust":20.8},"clouds":{"all":1},"dt":1606605601,"sys":{"type":1,"id":4861,"country":"US","sunrise":1606568201,"sunset":1606602118},"timezone":-21600,"id":4904381,"name":"Oak Park","cod":200}'

如何使这些数据可用?如何确保将正确的数据分配给正确的变量?

Questioner
Sam
Viewed
0
Shar 2020-11-29 07:43:11

你需要使用json模块解析数据,将其转换为可以轻松浏览的字典。

data = b'{"coord":{"lon":-87.74,"lat":41.9},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":46.49,"feels_like":35.37,"temp_min":45,"temp_max":48.2,"pressure":1018,"humidity":61},"visibility":10000,"wind":{"speed":13.87,"deg":210,"gust":20.8},"clouds":{"all":1},"dt":1606605601,"sys":{"type":1,"id":4861,"country":"US","sunrise":1606568201,"sunset":1606602118},"timezone":-21600,"id":4904381,"name":"Oak Park","cod":200}'

import json
data = json.loads(data.decode())

lon = data["coord"]["lon"]
lat = data["coord"]["lat"]
temp = data["main"]["temp"]
humidity = data["main"]["humidity"]