JSON to Rust Struct
Infer Rust structs with serde derives from a JSON sample.
About JSON to Rust Struct
Generate Rust structs with Serialize and Deserialize derives from a JSON sample. Paste JSON and typed structs appear as you type, with serde renames as needed.
How to use
- Paste JSON, or load a
.jsonfile (up to 5 MB). - Optionally change the root struct name (default
Root). It must start with a letter or underscore and contain only letters, digits and underscores. - The Rust code updates as you type. Copy it, or Download it as a
.rsfile. The output needs theserdecrate with thederivefeature, andserde_jsonwhen a field is typedserde_json::Value.
What it does
| JSON | Rust |
|---|---|
| string | String |
| integer | i64 |
| other number | f64 |
| boolean | bool |
| null, or mixed types | serde_json::Value |
| array | Vec<T> |
| nested object | a named struct, RootAddress |
| null in some items, or key missing from some items | Option<T> |
- Every struct is
puband derivesDebug,Clone,SerializeandDeserialize. Nested structs are listed before the struct that uses them. - Field names are snake_case. When every key in a struct is camelCase the struct gets
#[serde(rename_all = "camelCase")]; otherwise each key that differs from its field name gets#[serde(rename = "key")]. - Keys that are Rust keywords become raw identifiers such as
r#type, which serde serialises astype.
Example
{ "id": 1, "userName": "Ada", "tags": ["admin"] }
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Root {
pub id: i64,
pub user_name: String,
pub tags: Vec<String>,
}
Privacy
Inference runs in the page. No request is made and nothing is stored.
Frequently asked questions
- What is #[serde(rename_all = "camelCase")]?
- A container attribute that maps every field of a struct from Rust snake_case to camelCase in the JSON, so user_name is read and written as userName. It replaces a per-field #[serde(rename = "...")] when the whole struct follows one convention.
- Should I use Option<T> for nullable JSON?
- Yes. Option<T> deserialises JSON null as None and, for a struct field, also accepts a missing key as None. Serialising None writes null; add #[serde(skip_serializing_if = "Option::is_none")] if the key should be omitted instead.
- When should I use serde_json::Value?
- When a field has no fixed shape, for example when a sample mixes numbers and strings or only ever shows null. Value holds any JSON and can be matched or converted later, at the cost of compile-time typing.
- How do I parse JSON into a struct with serde?
- Derive Deserialize on the struct and call serde_json::from_str::<Root>(text) or from_slice for bytes. The result is a Result, so a missing required field or a wrong type returns an error that names the field.