如何处理天气API返回数据并在Python中赋值指定字段到变量
How to Parse Weather API Response and Assign Values to Variables
Let's walk through this step by step to get the exact values you need:
Step 1: Understand the Response Format
First off, your API response is a bytes object (the b'...' prefix gives that away) with HTML-escaped quotes (" instead of regular "). We need to fix both of these issues to turn it into a usable Python dictionary.
Step 2: Full Code Implementation
Here's the complete code to process the response and assign the variables exactly as you want:
import json import html # Your raw API response raw_response = 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}' # 1. Convert bytes to a UTF-8 string response_str = raw_response.decode('utf-8') # 2. Fix HTML-escaped quotes (turn " back into ") cleaned_response = html.unescape(response_str) # 3. Parse the cleaned string into a Python dictionary weather_data = json.loads(cleaned_response) # 4. Assign values to your target variables lon = weather_data['coord']['lon'] lat = weather_data['coord']['lat'] temp = weather_data['main']['temp'] humidity = weather_data['main']['humidity'] # Check if we got the right values print(f"lon = {lon}") print(f"lat = {lat}") print(f"temp = {temp}") print(f"humidity = {humidity}")
Step 3: What Each Part Does
- Byte-to-string conversion: APIs often return raw byte data, so
decode('utf-8')translates it into a readable string. - HTML unescaping: The
"characters are HTML entities for double quotes. Without fixing this, the JSON parser would throw an error—html.unescape()fixes this quickly. - JSON parsing:
json.loads()turns the cleaned string into a nested Python dictionary, letting you access specific values using their key names. - Variable assignment: We just traverse the nested keys (
coordfor longitude/latitude,mainfor temperature/humidity) to pull the exact values you need.
Step 4: Verify the Output
When you run this code, you'll get exactly the result you're targeting:
lon = -87.74 lat = 41.9 temp = 46.49 humidity = 61
内容的提问来源于stack exchange,提问作者AlgoTrading
相关产品推荐
相关产品推荐

