JSON format from the API
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mert
am 24 Mai 2024
Bearbeitet: Rik
am 25 Mai 2024
Hello, I'm going to fetch data from the OpenWeatherMap website as an app designer. The API will be in JSON format, but I keep getting errors. Can you help?
3 Kommentare
Akzeptierte Antwort
Abhishek Kumar Singh
am 25 Mai 2024
I generated an API key from https://home.openweathermap.org/api_keys and tried a simple MATLAB function, from which I was able to retrieve data without any errors.
Refer to the MATLAB function code below:
function getWeatherForecast(cityName, apiKey)
% Construct the API request URL
url = ['http://api.openweathermap.org/data/2.5/forecast?q=', cityName, '&appid=', apiKey, '&units=metric'];
try
% Send the request and get the response
responseData = webread(url);
% Process and display the temp for the first time point
firstTemp = responseData.list{1}.main.temp;
disp(['First temperature forecast for ', cityName, ' is: ', num2str(firstTemp), ' Celsius']);
catch ME
% Error handling
disp('Failed to retrieve or process weather data.');
disp(['Error: ', ME.message]);
end
end
You can call the function as:
% cityName - Name of the city (string)
% apiKey - Your OpenWeatherMap API key (string)
getWeatherForecast('London', 'YOUR_API_KEY')
The API gives you a lot of information organized in lists. You'll need to think about how you want to use this information and might need to add more steps to work with it properly. Here's a quick look at what kind of data you get from the API:
K>> responseData.list{1}
ans =
struct with fields:
dt: 1.7166e+09
main: [1×1 struct]
weather: [1×1 struct]
clouds: [1×1 struct]
wind: [1×1 struct]
visibility: 10000
pop: 0.3100
sys: [1×1 struct]
dt_txt: '2024-05-25 15:00:00'
K>> responseData.list{1}.main
ans =
struct with fields:
temp: 20.0400
feels_like: 19.4800
temp_min: 19.8100
temp_max: 20.0400
pressure: 1015
sea_level: 1015
grnd_level: 1012
humidity: 53
temp_kf: 0.2300
K>> responseData.list{1}.main.temp
ans =
20.0400
I hope this helps you get preliminary idea of how to get started. You can further process and visualize the forecast data in various formats within MATLAB.
2 Kommentare
Abhishek Kumar Singh
am 25 Mai 2024
Can you replace the line:
weatherData = fetchFiveDayForecast(cityName, apiKey);
with:
weatherData = app.fetchFiveDayForecast(cityName, apiKey);
and try again?
Let me know how it goes.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu JSON Format finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!