0

I have been working with a weather API and wish to assign values in the returned API data to certain variables. For example, I would like to assign the lon, lat, temp, and humidity values in the API data below to their own variables in my Python code, so the following is my result:

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

This is the data that I have received from my API request:

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}'

How do I make this data usable? How do I ensure that I get the right data to the right variables?

Hadrian
  • 917
  • 5
  • 10
AlgoTrading
  • 55
  • 2
  • 2
  • 9

1 Answers1

2

You need to parse the data with the json module, which converts it into a dict that you can easily navigate.

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"]
Shar
  • 448
  • 3
  • 8