Deserialize JSON Config With Serde
Derive Deserialize to load a configuration from JSON with defaults, rejecting unknown fields so typos in the config surface immediately.
Code
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ServerConfig {
port: u16,
#[serde(default = "default_workers")]
workers: usize,
host: String,
}
fn default_workers() -> usize {
4
}
fn load(source: &str) -> Result<ServerConfig, serde_json::Error> {
serde_json::from_str(source)
}
fn main() {
let json = r#"{"port": 8080, "host": "0.0.0.0"}"#;
match load(json) {
Ok(config) => println!("{config:?}"),
Err(error) => eprintln!("invalid config: {error}"),
}
}How it works
Structurally, expect the functions default_workers, load and main and nothing else.
Fallible operations return Result, forcing the caller to handle both arms explicitly. The match expression is exhaustive — the compiler enforces that no case is missing.
Points of care
- Plan for an install step:
serde::Deserializeis a real dependency, resolved by the package manager. - Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
The primary signature is fn default_workers() -> usize
The entry point wires load together — run it once and the whole demo flows.
Key statements
fn load(source: &str) -> Result<ServerConfig, serde_json::Error> {
serde_json::from_str(source)
}
fn default_workers() -> usize {
4
}
match load(json) {
Ok(config) => println!("{config:?}"),
Err(error) => eprintln!("invalid config: {error}"),
}
Interactive Tools for This Topic
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
FAQ
- How are errors reported?
- Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
- Which packages must be installed first?
- Yes. The imports resolve to `serde::Deserialize`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.