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"
endInline 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"
endThe generated module includes:
new/1andnew!/1for building a validated struct from atom-keyed attrs.from_json/1andfrom_json!/1for building a validated struct from a string-keyed JSON map.to_json/1for converting a generated struct back to a string-keyed map.validate/1for validating an existing generated struct.__schema__/1for 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.