JSON to Rust: structs that serde_json can read
Paste a JSON response or config and get structs with the right integer and float types, Option where data is patchy, and renames for keys Rust can't use as field names.
Paste or upload your JSON
Any valid JSON works: an API response, a config file or a list of records. This one has a long ID, a price with a trailing zero, a ZIP code with leading zeros and a list whose items don't all have the same keys:
{
"userId": 8901240544102066246,
"username": "rustacean",
"isActive": true,
"balance": 14.50,
"zip": "00501",
"tags": ["memory_safety", "fearless_concurrency"],
"profile": { "firstName": "Ferris", "lastName": "Crab", "age": 10 },
"orders": [
{ "id": 1, "total": 9.99 },
{ "id": 2, "total": 12, "note": "gift" }
]
}Name the struct and choose serde
There are two settings. The struct name is used for the top-level Rust struct; nested structs are named after their keys. "Use Serde" adds the serde derives and rename attributes. Without it you get plain structs, which is handy if you fill them by hand.
Read the generated structs
This is what the page writes for the JSON above. userId keeps every digit as an i64, balance is an f64, zip stays a String, and note is an Option because only one order has it.
// Cargo.toml:
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"
// Read your JSON with:
// let data: Root = serde_json::from_str(&json)?;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Root {
#[serde(rename = "userId")]
pub user_id: i64,
pub username: String,
#[serde(rename = "isActive")]
pub is_active: bool,
pub balance: f64,
pub zip: String,
pub tags: Vec<String>,
pub profile: Profile,
pub orders: Vec<Order>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Profile {
#[serde(rename = "firstName")]
pub first_name: String,
#[serde(rename = "lastName")]
pub last_name: String,
pub age: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Order {
pub id: i64,
pub total: f64,
pub note: Option<String>,
}Copy or download the .rs file
Copy the code or download generated_structs.rs, add serde and serde_json to Cargo.toml as the comment at the top says, and read your JSON with the serde_json::from_str line shown there. If you are new to serde, the serde_json walkthrough on our blog covers reading and writing JSON step by step.
What does the converter do?
It reads your JSON once and writes one Rust struct per object shape. Lists are merged item by item, so a key that only shows up in the tenth record still gets a field. Types are chosen so that serde_json can read the same JSON back without losing digits.
Have XML instead? The XML to Rust converter does the same for quick-xml, and JSON Schema to Rust works from a schema rather than sample data.
Frequently Asked Questions
What do I need in Cargo.toml?
Two crates: serde with the "derive" feature and serde_json. The comment at the top of the output spells out both lines and the serde_json::from_str call that reads your JSON into the generated type. Nothing else is needed; fields that hold mixed values use serde_json::Value, which comes with serde_json.
How does it pick between i64, u64, i128 and f64?
From the numbers exactly as you wrote them, not from a rounded JavaScript copy. Whole numbers that fit i64 become i64, so an ID like 8901240544102066246 stays an integer with every digit. Bigger positive values become u64, then i128 or u128. Anything with a decimal point or exponent, like 14.50 or 1e3, becomes f64. A quoted value such as "00501" is a String, so its leading zeros survive.
Why are some fields Option<T>?
Every item of a list is looked at, not just the first one. If a key is missing from some items or holds null somewhere, the field becomes Option<T>. serde fills a missing Option field with None, so the same struct reads all of your items. A field that mixes kinds of values, such as a number in one item and text in another, becomes serde_json::Value.
What happens to keys that are not valid Rust names?
Field names are turned into snake_case, and the original key is kept with #[serde(rename = "...")] whenever the two differ. Keywords such as type or fn become raw identifiers (r#type), which serde still matches to "type"; self and crate get a trailing underscore. Keys starting with a digit get a field_ prefix, and keys that end up with the same name are numbered. Struct names that would hide String, Option or Vec get a Data suffix.
Can I paste a JSON array instead of an object?
Yes. The structs describe one item of the array, and the comment at the top shows the type to read it into, for example Vec<Root>. A plain value or a list of plain values has no object to describe, so you get a short message instead of code.
Is my JSON sent anywhere?
No. The structs are generated in your browser and your JSON is not uploaded or kept; reloading the page starts with an empty editor.
Related Tools
JSON Schema to Rust
Generate Rust types from JSON Schema with validation
YAML to Rust
Convert YAML configuration to Rust structs with serde
TOML to Rust
Convert TOML configuration to Rust config structs
XML to Rust
Convert XML data to Rust structs with serde serialization support
CSV to Rust
Convert CSV data to Rust structs with field mapping
TypeScript to Rust
Convert TypeScript interfaces and types to Rust structs