如何在Flutter中解析Openweather API的JSON获取description与temp值
No worries, pulling those fields is totally straightforward once you get the hang of the API's JSON structure! Let's break this down step by step.
First, here's the key part of the JSON response you'll receive (trimmed to focus on your target fields):
{ "weather": [ { "id": 300, "main": "Drizzle", "description": "light intensity drizzle", "icon": "09d" } ], "main": { "temp": 280.32, "pressure": 1012, "humidity": 81 } }
Quick notes on structure:
descriptionlives inside the first element of theweatherarray (the API returns an array here even for a single weather entry)tempis nested under the top-levelmainobject
Here are solutions for common tools/languages:
Python (using requests library)
This is one of the most common approaches for server-side or script-based work:
import requests api_url = "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22" response = requests.get(api_url) weather_data = response.json() # Extract your target fields weather_desc = weather_data['weather'][0]['description'] temp = weather_data['main']['temp'] print(f"Weather: {weather_desc}") print(f"Temperature: {temp} K") # Temp is in Kelvin by default
JavaScript (browser or Node.js)
Browser-side with fetch:
fetch('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22') .then(res => res.json()) .then(data => { const weatherDesc = data.weather[0].description; const temp = data.main.temp; console.log(`Current weather: ${weatherDesc}`); console.log(`Current temp: ${temp} K`); }) .catch(err => console.error('Failed to fetch data:', err));
Node.js with axios:
First install axios via npm: npm install axios
const axios = require('axios'); axios.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22') .then(res => { const weatherDesc = res.data.weather[0].description; const temp = res.data.main.temp; console.log(`Current weather: ${weatherDesc}`); console.log(`Current temp: ${temp} K`); }) .catch(err => console.error('Failed to fetch data:', err));
Command Line (using jq)
If you prefer working directly in the terminal, jq is a lightweight tool for parsing JSON:
curl "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22" | jq '.weather[0].description, .main.temp'
This will print the two values directly in your terminal.
Pro tip: In production code, add checks to handle edge cases (like empty weather arrays or API error responses) to avoid unexpected crashes!
内容的提问来源于stack exchange,提问作者Christian

