From bb410d002f14627e28cbabd8d48ffab5803b3ee7 Mon Sep 17 00:00:00 2001 From: Candifloss Date: Thu, 18 Sep 2025 22:42:31 +0530 Subject: [PATCH] Parse json data - Process json response - Extract required json fields - Use the extracted fields --- Cargo.toml | 2 +- src/main.rs | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c9bcf0d..9abb3bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,6 @@ edition = "2024" toml = "0.9.6" dirs = "6.0.0" serde = { version = "1.0.225", features = ["derive"] } -reqwest = {version = "0.12.23", features = ["blocking"] } +reqwest = {version = "0.12.23", features = ["blocking", "json"] } serde_json = "1.0.145" diff --git a/src/main.rs b/src/main.rs index 2b1c0ed..a528c1a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,30 @@ struct Config { general: General, } +#[derive(Debug, Deserialize)] +struct Weather { + main: String, + icon: String, +} + +#[derive(Debug, Deserialize)] +struct Main { + temp: f32, +} + +#[derive(Debug, Deserialize)] +struct Sys { + country: String, +} + +#[derive(Debug, Deserialize)] +struct WeatherResponse { + name: String, + sys: Sys, + weather: Vec, + main: Main, +} + fn main() -> Result<(), Box> { let mut config_path = dirs::config_dir().ok_or("No config dir found")?; config_path.push("candywidgets/openweathermap.toml"); @@ -28,8 +52,14 @@ fn main() -> Result<(), Box> { config.general.units, config.general.city_id, config.general.api_key ); - let resp = blocking::get(&url)?.text()?; - println!("Weather report:\n{resp}"); + let resp = blocking::get(&url)?.json::()?; + + println!("City: {}, {}", resp.name, resp.sys.country); + if let Some(w) = resp.weather.first() { + println!("Weather: {}", w.main); + println!("Icon: {}", w.icon); + } + println!("Temperature: {}°C", resp.main.temp); Ok(()) }