How to use the JSON to Rust Struct
- 1
Paste JSON
Any object or array of objects works — an API response, a config file or a message from a queue.
- 2
Set the root struct name
For example Release; child structs take PascalCase names from their keys.
- 3
Generate
Each struct derives Debug, Clone, Serialize and Deserialize, with serde attributes only where needed.
- 4
Add the crates
Put serde (with derive) and serde_json in Cargo.toml, paste the code into a module and call serde_json::from_str.
Features
Idiomatic field names
camelCase or hyphenated keys become snake_case fields, with #[serde(rename = "…")] keeping the wire name.
Option for gaps
Values that are null or missing in your sample become Option<T>.
Clean serialisation
Fields missing from some items also get skip_serializing_if = "Option::is_none", so None is not written out as null.
Raw identifiers
A key like type or match becomes r#type, a legal Rust field name.
serde_json::Value fallback
Always-null or mixed values fall back to Value so parsing never fails on them.
Local only
The conversion runs in your browser.
Who uses it — and for what
CLI authors
Parse GitHub, GitLab or package-registry API responses in a command-line tool.
Web backend devs
Define request and response types for Axum or Actix handlers.
Data engineers
Read JSON lines or event logs into typed structs for processing.
Rust learners
See how Option, Vec and derives describe real-world JSON.
How the types are inferred
The generator reads your sample and infers a type for every field: strings, integers and decimals, booleans, nested objects (each gets its own named Rust type) and arrays. If an array holds several objects, all of them are merged — fields missing from some items become optional and fields that are sometimes null become nullable, so one representative response is usually enough. Field names that aren’t valid identifiers are converted and mapped back to the original JSON key.
Using the Rust code
Structs derive Serialize and Deserialize from serde; parse with serde_json::from_str::<Root>(&text)?. Fields use snake_case with #[serde(rename = "…")] where the JSON key differs. Optional or nullable values are Option<T>, optional ones also skip serialising when None. Integers are i64 and decimals f64; unknown shapes fall back to serde_json::Value. Add serde = { version = "1", features = ["derive"] } and serde_json to Cargo.toml.
Everything runs in your browser — your code and data are never uploaded, so it is safe to paste private config files and API responses.
How serde reads the generated structs
The derive macros produce code at compile time, so there is no reflection cost when parsing. A few serde rules explain why the output looks the way it does:
- Unknown fields are ignored. If the API sends keys your struct does not declare, serde skips them. Add
#[serde(deny_unknown_fields)]to a struct when you would rather fail loudly. - Missing Option fields become None. serde treats an absent key as
NoneforOptionfields. The extra#[serde(default)]the generator adds on optional fields makes that intent explicit. - Non-optional fields are required. A missing
Stringori64field is an error, which is usually what you want for data you rely on. - Raw identifiers are transparent. serde already serialises
r#typeastype; the rename attribute is harmless and keeps the mapping obvious to readers.
Choosing tighter Rust types
The generator picks broad, safe types: every integer is i64, every fraction f64, every string String. Narrowing them encodes more of the contract in the type system:
| Field kind | Generated | Consider |
|---|---|---|
| Sizes, counts | i64 | u64 or u32 — they are never negative |
| Fixed set of strings | String | An enum with #[serde(rename_all = "lowercase")] |
| Timestamps | String | chrono::DateTime<Utc> or time::OffsetDateTime with their serde features |
| Large text you only read | String | &'a str or Cow<'a, str> with a lifetime, to borrow from the input |
| Free-form metadata | a struct | HashMap<String, serde_json::Value> |
The derives on every struct — Debug for printing and Clone for copying — cost nothing until used, so leave them unless you have a reason to remove them.
Worked examples
A release from a code-hosting API
Input:
{"tag_name": "v2.4.0", "draft": false, "type": "release", "downloadCount": 3120,
"published_at": "2026-10-11T12:00:00Z",
"assets": [{"name": "app-linux.tar.gz", "size": 8812201, "checksum": null},
{"name": "app-win.zip", "size": 9120044, "checksum": "ab12"}],
"body": null}Generated output:
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Root {
pub tag_name: String,
pub draft: bool,
#[serde(rename = "type")]
pub r#type: String,
#[serde(rename = "downloadCount")]
pub download_count: i64,
pub published_at: String,
pub assets: Vec<Asset>,
pub body: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Asset {
pub name: String,
pub size: i64,
pub checksum: Option<String>,
}Keys already in snake_case (tag_name) need no attribute. checksum was null in one asset and a string in the other, so it is Option<String>. body was only ever null, so it is a serde_json::Value; in practice you would make it Option<String>.
Parsing with error handling
fn main() -> Result<(), Box<dyn std::error::Error>> {
let text = std::fs::read_to_string("release.json")?;
let release: Root = serde_json::from_str(&text)?;
println!("{} has {} assets", release.tag_name, release.assets.len());
Ok(())
}If the JSON does not match, serde_json returns an error naming the line, column and the field it expected.
Pro tips
- If every key in a struct is camelCase, replace the per-field renames with one #[serde(rename_all = "camelCase")] above the struct.
- Use serde_json::from_reader with a BufReader for large files instead of reading the whole file into a String first.
- Run cargo clippy after pasting; it will point out unused imports or fields you may want to drop.
Glossary
- serde
- Rust’s standard framework for serialising and deserialising data structures.
- Derive macro
- An attribute such as #[derive(Deserialize)] that generates trait implementations at compile time.
- Option<T>
- Rust’s type for a value that may be absent: Some(value) or None.
- Raw identifier
- A name prefixed with r# so a keyword like type can be used as an identifier.
Frequently asked questions
Which crates do I need?
serde (with the derive feature) and serde_json.
Why Option<T>?
It represents null or missing JSON values safely.
Can I use rename_all instead?
Yes — #[serde(rename_all = "camelCase")] on the struct replaces per-field renames when keys are consistent.
Why i64 and not u64 for sizes?
JSON does not say whether a number can be negative, so the generator picks the signed type. Switch to u64 if negatives are impossible.
Does it work with no_std or other formats?
The structs only derive serde traits, so they also work with formats like TOML, YAML or bincode through their serde crates.
Why is a field serde_json::Value?
Your sample had it as null everywhere, an empty array or mixed types, so no concrete type could be inferred.
Last updated 2026-11-28 · Built by Vinayak Agarwal · Part of Developer & Web (77 tools)