AutoStruct.JsonSchema (AutoStruct v0.3.0)

Copy Markdown View Source

Generates structs and conversion helpers from JSON Schema.

AutoStruct.JsonSchema is a compile-time macro. It reads either an inline schema with :schema or a schema file with :file, generates a struct from the schema's top-level properties, and delegates validation to Exonerate.

File-based schemas are useful when the schema uses local references or should be shared with other tools:

defmodule Person do
  use AutoStruct.JsonSchema, file: "priv/schemas/person.json"
end

Inline schemas are useful for small modules and tests:

iex> defmodule Elixir.AutoStruct.DocInlinePerson do
...>   use AutoStruct.JsonSchema,
...>     schema: """
...>     {
...>       "type": "object",
...>       "properties": {
...>         "first_name": { "type": "string" },
...>         "age": { "type": "integer" }
...>       },
...>       "required": ["first_name"]
...>     }
...>     """
...> end
iex> {:ok, created} = AutoStruct.DocInlinePerson.new(first_name: "Ada", age: 36)
iex> created.first_name
"Ada"
iex> {:ok, loaded} = AutoStruct.DocInlinePerson.from_json(%{"first_name" => "Ada", "age" => 36})
iex> loaded.age
36
iex> {:ok, encoded} = AutoStruct.DocInlinePerson.new(first_name: "Ada", age: 36)
iex> AutoStruct.DocInlinePerson.to_json(encoded)
%{"age" => 36, "first_name" => "Ada"}
iex> {:error, {:validation_failed, _}} = AutoStruct.DocInlinePerson.validate(struct(AutoStruct.DocInlinePerson, first_name: 123))

The same API is generated for file-based schemas:

defmodule Person do
  use AutoStruct.JsonSchema,
    file: "examples/schemas/person.json"
end

The generated module includes:

  • new/1 and new!/1 for building a validated struct from atom-keyed attrs.
  • from_json/1 and from_json!/1 for building a validated struct from a string-keyed JSON map.
  • to_json/1 for converting a generated struct back to a string-keyed map.
  • validate/1 for validating an existing generated struct.
  • __schema__/1 for compile-time schema metadata.

Nested JSON Schema objects and arrays are validated by Exonerate, but only the top-level schema object is cast into a struct. Nested objects remain maps unless the caller transforms them separately.

Generated structs implement Elixir's built-in JSON.Encoder. When Jason is available at compile time, AutoStruct also emits a compatible Jason.Encoder implementation.