JSON to Rust Struct (Serde)
Paste JSON and get Rust structs that derive serde's Serialize and Deserialize, with Option for fields that may be missing. Free, no signup, and generated in your browser so your data stays local.
16 lines · processed in your browser, nothing is uploaded
Rust output · root.rs
Generated code appears here.Example: JSON to Rust
This JSON sample, with the root type named User, produces the Rust below using the default options.
{
"id": 1024,
"name": "Ada Lovelace",
"email": "ada@example.com",
"active": true,
"score": 98.5,
"tags": [
"admin",
"beta"
],
"address": {
"city": "London",
"postcode": "NW1 6XE"
}
}use serde::{Serialize, Deserialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: i64,
pub name: String,
pub email: String,
pub active: bool,
pub score: f64,
pub tags: Vec<String>,
pub address: Address,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Address {
pub city: String,
pub postcode: String,
}
How to convert JSON to Rust
- 1Paste a JSON object or array into the input.
- 2Select Rust as the output language.
- 3Name the root struct, for example Config.
- 4Adjust options such as derives or visibility if available.
- 5Copy the structs into your crate and parse with serde_json::from_str.
serde derive basics
Add serde with the derive feature and serde_json to Cargo.toml, then put #[derive(Serialize, Deserialize)] on each struct. Parse with let cfg: Config = serde_json::from_str(&text)?;.
Rust field names are snake_case. Use #[serde(rename = "userId")] on a field, or #[serde(rename_all = "camelCase")] on the struct, to match the JSON keys.
Option and missing fields
A field typed Option<T> accepts both null and a missing key and deserializes to None. A non-Option field with a missing key is an error, which is usually what you want for required data.
Add #[serde(skip_serializing_if = "Option::is_none")] if you want None fields omitted when serializing back to JSON.
Numbers and unknown shapes
Check numeric types against real data: an ID that fits i64 in your sample might need u64, and a value that is sometimes fractional needs f64.
For parts of the payload whose shape varies, serde_json::Value keeps the raw JSON so you can handle it later.