Skip to main content
Back to tools

JSON to Rust Struct

Generate serde structs with derive macros from a JSON object

About JSON to Rust Struct

Writes Rust structs deriving Debug, Clone, Serialize and Deserialize, with snake_case fields and #[serde(rename)] wherever a field name differs from its JSON key. Whole numbers map to i64, decimals to f64, nulls and keys absent from some array items to Option<T>, and mixed or empty values use serde_json::Value. Suited to typing API responses in reqwest clients; check numeric types against real data, since generation runs client-side from one sample.

Category: Converters.

Frequently asked questions

Which crates does the generated Rust code need?

▾

serde with the derive feature and serde_json, added with cargo add serde --features derive and cargo add serde_json. serde_json parses the text and also provides the serde_json::Value type used for untyped fields.

Why do some fields use r#type or a trailing underscore?

▾

Keys that are Rust keywords become raw identifiers such as r#type or r#match, each with an explicit rename to the original key. self, super and crate can't be raw identifiers, so they become self_, super_ and crate_ instead.

What happens when a key is missing from some array elements?

▾

All elements of an array are merged into one struct, and a key absent from at least one of them becomes Option<T>. Serde fills a missing Option field with None, so no #[serde(default)] attribute is needed.

How do I parse JSON into the generated structs?

▾

Use let root: Root = serde_json::from_str(&text)?; for an object, or parse into RootList, an alias for Vec<Root>, when the JSON is a top-level array. Serde ignores unknown keys by default; add #[serde(deny_unknown_fields)] to a struct to reject them.

Related tools