Loading Rust to JSON Schema Converter...

How to Generate a JSON Schema from Rust Structs

A Rust service that speaks JSON through serde already knows the shape of every message, but the frontend, the API docs or the test suite usually needs that shape written down as a schema. Paste the structs here and you get one that matches what serde really writes, key names and number limits included.

Step 1

Paste your Rust types

Paste the struct and enum definitions with their #[derive] and #[serde] attributes, or upload a .rs file. A whole file is fine: use lines, impl blocks and functions are skipped, and types inside mod blocks are read too. Click Sample to try a small example first.

use serde::Serialize;

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    pub order_id: u64,
    pub total: f64,
    pub note: Option<String>,
    pub items: Vec<Item>,
    pub status: Status,
}

#[derive(Serialize)]
pub struct Item {
    pub sku: String,
    pub quantity: u16,
}

#[derive(Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Pending,
    Shipped,
}
Step 2

Read the generated schema

A moment after you stop typing, the schema appears on the right. Every type gets an entry under $defs, and the top of the schema points at the first type no other type uses. A blue box above it lists anything that needed a decision, such as fields that accept any value. A syntax mistake in the Rust code gives you the line and column instead.

The example above comes out like this. rename_all turns order_id into orderId, note is optional because it is an Option, and the u64 and u16 fields carry their real limits:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Order",
  "$ref": "#/$defs/Order",
  "$defs": {
    "Order": {
      "title": "Order",
      "type": "object",
      "properties": {
        "orderId": {
          "type": "integer",
          "minimum": 0,
          "maximum": 18446744073709551615
        },
        "total": {
          "type": "number"
        },
        "note": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ]
        },
        "items": {
          "type": "array",
          "items": {
            "$ref": "#/$defs/Item"
          }
        },
        "status": {
          "$ref": "#/$defs/Status"
        }
      },
      "required": [
        "orderId",
        "total",
        "items",
        "status"
      ]
    },
    "Item": {
      "title": "Item",
      "type": "object",
      "properties": {
        "sku": {
          "type": "string"
        },
        "quantity": {
          "type": "integer",
          "minimum": 0,
          "maximum": 65535
        }
      },
      "required": [
        "sku",
        "quantity"
      ]
    },
    "Status": {
      "title": "Status",
      "type": "string",
      "enum": [
        "pending",
        "shipped"
      ]
    }
  }
}
Step 3

Copy or download it

Copy puts the schema on your clipboard and Download saves it as schema.json. Point any JSON Schema 2020-12 validator at it, such as ajv with its Ajv2020 class, to check JSON your service sends or receives.

What is a JSON Schema for Rust Types?

JSON Schema describes which keys a JSON document has, what type each value is and which keys must be there. A Rust struct says the same things in its own words, so most of the work is translating types, plus following serde's attributes, because they decide the real key names and how enums look on the wire.

Starting from JSON instead of Rust? Use JSON to JSON Schema. To test documents against the result, try the JSON Schema Validator, and JSON Schema to Rust goes the other way.

Frequently Asked Questions

What does the schema describe, exactly?

The JSON that serde_json writes for your types. Field names follow rename and rename_all, skipped fields are left out, flatten pulls the inner struct's fields up, and transparent and newtype structs take the shape of the value they wrap. The code is only read, never compiled or run, and values like a vec![...] of struct literals are not type definitions, so the page asks for the definitions instead.

How are Rust integers and floats written?

Every integer type gets "type": "integer" with its real range, so a u8 is 0 to 255 and a u64 is 0 to 18446744073709551615. Those limits are written with every digit, so a long ID like 8901240544102066246 is checked against the right bound. NonZero types leave out 0, and usize and isize are treated as 64-bit. f32 and f64 become "number"; note that serde_json writes NaN and infinity as null, which the schema does not allow.

Which fields end up in required?

Fields serde always needs when reading. Option fields are allowed to be null and may also be left out, because serde reads a missing Option as None. Fields with #[serde(default)] (on the field or the struct), skip_serializing_if, skip_serializing or skip_deserializing are optional too. With #[serde(deny_unknown_fields)] the object gets "additionalProperties": false; otherwise extra keys are allowed, just like serde allows them.

How are enums handled?

Plain enums become a string enum with serde's names. Enums with data follow serde's tagging: by default a variant is written as {"Variant": value}, #[serde(tag = "type")] puts the tag inside the object, tag plus content gives {"t": ..., "c": ...}, and #[serde(untagged)] lists each variant's shape under anyOf. Enums deriving Serialize_repr from serde_repr become an integer enum with their discriminants, counted the same way Rust counts them.

What about maps, tuples, chrono dates and serde_json::Value?

HashMap and BTreeMap become objects whose values follow the map's value type; integer keys are checked with a digits-only pattern, since serde_json writes them as text. Tuples and tuple structs become fixed-length arrays, [T; N] arrays get their length, and sets get uniqueItems. Uuid, Url, chrono DateTime and NaiveDate get a string with the matching format, Decimal stays a string because that is how rust_decimal writes it, and serde_json::Value accepts anything.

How is this different from the schemars crate?

schemars derives a schema at compile time and is the better choice inside a build. This page is for when you want a schema without adding a dependency or compiling anything, for example to share with a frontend team or to check an API response. It follows the same serde attributes, but types it cannot see (from other crates you did not paste) accept any value, and the notes box says which ones.

Is my code uploaded anywhere?

No. The conversion runs in your browser, the code is not sent to our server, and nothing is kept: a reload starts with an empty editor. Uploaded .rs files are read in the browser too, up to 10 MB.