Zoi.JSONSchema (Zoi v0.10.7)

View Source

JSON Schema is a declarative language for annotating and validating JSON document's structure, constraints, and data types. It helps you standardize and define expectations for JSON data.

Zoi provides functionality to convert its type definitions into JSON Schema format, enabling seamless integration with systems that utilize JSON Schema for data validation and documentation.

Example

iex> schema = Zoi.object(%{name: Zoi.string(), age: Zoi.integer()})
iex> Zoi.to_json_schema(schema)
%{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  type: :object,
  properties: %{
    name: %{type: :string},
    age: %{type: :integer}
  },
  required: [:name, :age],
  additionalProperties: false
}

Supported Types

The following Zoi types are supported for conversion to JSON Schema:

Metadata

Zoi.to_json_schema/1 can also incorporate description and example metadata into the resulting JSON Schema:

iex> schema = Zoi.string(description: "A simple string", example: "Hello, World!")
iex> Zoi.to_json_schema(schema)
%{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  type: :string,
  description: "A simple string",
  example: "Hello, World!"
}

Limitations

  • Complex types or custom types not listed above will raise an error during conversion.
  • Some advanced Zoi features may not have direct equivalents in JSON Schema.
  • Refinements are partially supported, primarily for string patterns and length constraints.
  • Additional properties in objects are disallowed by default (additionalProperties: false).

References

Summary

Functions

encode(schema)

@spec encode(Zoi.schema()) :: map()