Turn a JSON sample into Rust structs ready for serde. Each struct derives Debug, Clone, Serialize, Deserialize; field names follow Rust's snake_case convention and are tied back to the original key with #[serde(rename)] when they differ.
It's a starting point when you want typed reqwest responses, need a request type for an axum or actix-web Json<T> extractor, or are writing a CLI that parses log or event JSON.
Type name (for example AccessLog)..rs file and add serde (with the derive feature) and serde_json to Cargo.toml.serde_json::from_str::<AccessLog>(&body)? or resp.json::<AccessLog>().await?.{
"timestamp": 1714550400,
"level": "warn",
"type": "http_request",
"status": 503,
"latency_ms": 1250.7,
"headers": [{ "name": "user-agent", "value": "curl/8.4" }],
"trace_id": null
}use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessLog {
pub timestamp: i64,
pub level: String,
#[serde(rename = "type")]
pub type_: String,
pub status: i64,
pub latency_ms: f64,
pub headers: Vec<Header>,
pub trace_id: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Header {
pub name: String,
pub value: String,
}
type is a Rust keyword, so the field is type_ with #[serde(rename = "type")]. Integers are i64 regardless of size, and latency_ms is f64. trace_id is only ever null, so its type is unknown and it stays serde_json::Value; replace it with the real type, e.g. Option<String>.
#[derive(Debug, Clone, Serialize, Deserialize)] and pub fields on every struct.#[serde(rename = "originalKey")] when the key differs from the snake_case field name.Option<T> with #[serde(default, skip_serializing_if = "Option::is_none")].null: plain Option<T> without attributes.i64 for integers, f64 for decimals, bool, String, Vec<T>, and serde_json::Value for mixed types.type, match or ref get a trailing underscore (type_).pub type Root = Vec<RootItem>;.Replace serde_json::Value lookups like ["status"].as_i64() with resp.json::<AccessLog>() so a misspelled field fails at compile time.
Generate a struct from the JSON a client sends and accept it as Json(payload): Json<CreateOrder>; requests with missing or mistyped fields are rejected by the framework before your handler code runs.
Build a struct from one log line, then deserialize each line from BufReader::lines() to get a per-field aggregation tool in a few lines.
i64, however small. Narrow them yourself where the range is known, e.g. u16 status codes or u32 counters.i64 or String. Switching to chrono or time types requires enabling those crates' serde features.serde_json::Value writes the full path, so no extra use is needed, but the serde_json dependency is.#[serde(rename_all = "camelCase")]. If the keys follow one convention, you can collapse them yourself."level": "warn", are good candidates for an enum afterwards.#[serde(default)]?serde already fills a missing Option with None, but an explicit default keeps accepting missing keys if you later change the type to something like Vec<T>. skip_serializing_if omits None fields when writing JSON back, preserving the original shape.
Both become Option<T>, but only fields whose key can be absent get the default and skip_serializing_if attributes. A field that is always present but sometimes null is written back as null.
&str fields and a 'de lifetime?Zero-copy fields (&'a str) can't outlive the input buffer, which is awkward for typical response handling. Owned String is the default; switch hot fields to Cow<'a, str> if performance matters.
Default or PartialEq derives?The output derives only Debug, Clone, Serialize and Deserialize. Add more to the derive list yourself when all field types support them (serde_json::Value implements PartialEq).