Skip to main content

Crate specta_jsonschema

Crate specta_jsonschema 

Source
Expand description

JSON Schema exporter and importer for Specta.

This crate provides bidirectional conversion between Specta types and JSON Schema:

  • Export Specta types to JSON Schema (Draft 7, 2019-09, or 2020-12)
  • Import JSON Schema definitions as Specta DataTypes

§Features

  • Bidirectional conversion: Export to JSON Schema and import from JSON Schema
  • Multiple schema versions: Support for Draft 7 (default), Draft 2019-09, and Draft 2020-12
  • Serde integration: Use specta-serde in userspace before export
  • Flexible layouts: Single file with $defs or separate files per type
  • schemars ecosystem: Compatible with the schemars crate for interoperability

§Usage

§Exporting to JSON Schema

use serde::{Deserialize, Serialize};
use specta::{Type, Types};
use specta_jsonschema::{JsonSchema, SchemaVersion};

#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct User {
    pub id: u32,
    pub name: String,
    pub email: Option<String>,
}

fn main() {
    let types = Types::default()
        .register::<User>();

    // Export to JSON Schema
    let schema = JsonSchema::default()
        .schema_version(SchemaVersion::Draft7)
        .export(&types, specta_serde::Format)
        .unwrap();

    println!("{}", schema);
}

§With Serde Integration

use serde::{Deserialize, Serialize};
use specta::{Type, Types};
use specta_jsonschema::JsonSchema;

#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct User {
    pub user_id: u32,
    #[serde(rename = "fullName")]
    pub name: String,
}

fn main() {
    let types = Types::default().register::<User>();

    JsonSchema::default()
        .export_to("./schema.json", &types, specta_serde::Format)
        .unwrap();
}

§Importing from JSON Schema

use schemars::Schema;
use specta_jsonschema::import::from_schema;

let schema: Schema = serde_json::from_str(r#"{
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer" }
    },
    "required": ["name"]
}"#).unwrap();

let datatype = from_schema(&schema).unwrap();

§Multiple Output Layouts

use specta_jsonschema::{JsonSchema, Layout};

// Single file with all types in $defs
JsonSchema::default()
    .layout(Layout::SingleFile)
    .export_to(
        "./schema.json",
        &types,
        specta_serde::Format,
    )
    .unwrap();

// Separate file per type, organized by module
JsonSchema::default()
    .layout(Layout::Files)
    .export_to(
        "./schemas/",
        &types,
        specta_serde::Format,
    )
    .unwrap();

Modules§

import

Structs§

JsonSchema
JSON Schema exporter configuration

Enums§

Error
Layout
Controls how JSON schemas are organized in output
SchemaVersion
JSON Schema version specification

Functions§

to_astDeprecated