Skip to Content

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.

INPUT JSON100% local in browser
models.rs
// 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:

order.json
{
  "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:

models.rs
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,
}

How JSON types map to Rust

JSON valueRust
stringString
whole numberi64
number with a fraction, or a mix of bothf64
true or falsebool
null, or a key some objects lackOption<T>
arrayVec<T>
objectits own struct
mixed types, or only nullserde_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.

Cargo.toml
[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:

src/main.rs
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:

output
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

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: