Parse json data

- Process json response
- Extract required json fields
- Use the extracted fields
This commit is contained in:
Candifloss 2025-09-18 22:42:31 +05:30
parent bebfc6887f
commit bb410d002f
2 changed files with 33 additions and 3 deletions

View File

@ -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"

View File

@ -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<Weather>,
main: Main,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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::<WeatherResponse>()?;
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(())
}