Code generator tool
JSON to Rust Structs
Paste a JSON object or array and get Rust structs ready for serde: snake_case fields with rename attributes, Option for nulls and missing keys, and Vec for arrays. It runs in your browser, so your JSON never leaves your machine.
// Paste JSON on the left (or click 'Load Sample') to generate Rust serde structs.What the converter generates
Here's an order with a nested customer, a list of items and a coupon that's null:
{
"orderId": 1042,
"customer": { "name": "Ada", "country": "GB" },
"items": [
{ "sku": "KB-01", "price": 49.5, "qty": 1 },
{ "sku": "MS-02", "price": 19, "qty": 2, "giftWrap": true }
],
"couponCode": null
}With the root name set to Order, the Rust tab produces:
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
#[serde(rename = "orderId")]
pub order_id: i64,
pub customer: Customer,
pub items: Vec<Item>,
#[serde(rename = "couponCode")]
pub coupon_code: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Item {
pub sku: String,
pub price: f64,
pub qty: i64,
#[serde(rename = "giftWrap", skip_serializing_if = "Option::is_none")]
pub gift_wrap: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Customer {
pub name: String,
pub country: String,
}- Field names follow Rust style.
orderIdbecomesorder_id, and#[serde(rename = "orderId")]keeps the JSON name for reading and writing. - Each nested object gets a struct named after its key:
customerbecomesCustomer, and the objects initemsbecomeItem. - All items share one struct. Only the second item has
giftWrap, so it's anOption<bool>, andskip_serializing_ifleaves it out again when you write JSON. - Numbers widen when they need to.
priceholds49.5and19, so it'sf64. Whole numbers on their own becomei64. - A key that's only ever
nullgives no type to go on, socouponCodebecomesOption<serde_json::Value>. Change it toOption<String>once you know what it holds.
How JSON types map to Rust
| JSON value | Rust |
|---|---|
| string | String |
| whole number | i64 |
| number with a fraction, or a mix of both | f64 |
true or false | bool |
null, or a key some objects lack | Option<T> |
| array | Vec<T> |
| object | its own struct |
mixed types, or only null | serde_json::Value |
Keys that are Rust keywords become raw identifiers: type is written r#type, and serde still reads it as "type". The few keywords that can't be raw (self, super and crate) get a trailing underscore and a rename. A struct whose name would shadow Option, Vec or String gets a number added instead.
Use the structs in your project
Add serde with its derive feature, and serde_json, to Cargo.toml. Or run cargo add serde --features derive and then cargo add serde_json.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Save the generated code as src/models.rs. Then serde_json::from_str parses JSON into an Order, and serde_json::to_string_pretty turns it back into JSON:
mod models;
use models::Order;
fn main() -> Result<(), serde_json::Error> {
let json = r#"{
"orderId": 1042,
"customer": { "name": "Ada", "country": "GB" },
"items": [{ "sku": "KB-01", "price": 49.5, "qty": 1 }],
"couponCode": null
}"#;
let order: Order = serde_json::from_str(json)?;
println!("{} ordered {} item(s)", order.customer.name, order.items.len());
// Back to JSON: giftWrap is left out because it is None.
println!("{}", serde_json::to_string_pretty(&order)?);
Ok(())
}When serde_json rejects your JSON
The structs only know the JSON you pasted. If real data leaves out a key that your sample always had, parsing fails. Remove qty from the item above and the program stops with:
Error: Error("missing field `qty`", line: 4, column: 51)A value that is sometimes null fails the same way, with invalid type: null, expected struct Customer. In both cases, wrap the field's type in Option. Better still, paste several real responses as one JSON array: the converter merges them into one struct, and every key that's missing or null in any of them becomes an Option.
Tips for real APIs
- One attribute instead of many renames. If every key is camelCase, replace the per-field renames with
#[serde(rename_all = "camelCase")]on the struct. - Pick tighter number types.
i64fits almost any whole number in JSON. When you know the range, useu32oru8: serde then rejects values that don't fit. - Catch API changes. serde ignores keys your struct doesn't have. Add
#[serde(deny_unknown_fields)]to make an unexpected key an error instead.
New to structs? The Rust Structs lesson covers defining and using them, and Structs by Example builds a small program with #[derive(Debug)]. If the compiler complains, see E0063: missing field in initializer and E0609: no field on type.
Convert JSON to other languages
The converter above has a tab for each language. These pages explain the output for the other two: