AutoStruct - generate Elixir structs from JSON Schema

Hey everyone,

I just published auto_struct, a small library for generating Elixir structs from JSON Schema.

The goal is pretty focused: you define a JSON Schema, and AutoStruct generates a struct plus a few helpers around it. Validation is handled by Exonerate, so AutoStruct is mostly a thin codegen layer around a real JSON Schema validator.

A simple example:

defmodule Person do
  use AutoStruct.JsonSchema,
    schema: """
    {
      "type": "object",
      "properties": {
        "first_name": { "type": "string" },
        "age": { "type": "integer", "minimum": 0 }
      },
      "required": ["first_name"]
    }
    """
end

Then you get:

Person.new(first_name: "Ada", age: 36)
# {:ok, %Person{first_name: "Ada", age: 36}}

Person.new!(first_name: "Ada", age: 36)
# %Person{first_name: "Ada", age: 36}

Person.from_json(%{"first_name" => "Ada", "age" => 36})
# {:ok, %Person{first_name: "Ada", age: 36}}

JSON.encode!(Person.new!(first_name: "Ada", age: 36))
# "{\"age\":36,\"first_name\":\"Ada\"}"

It supports inline schemas and file-based schemas:

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

A couple notes on the current shape of the library:

  • It validates nested objects and arrays through Exonerate.
  • It uses Elixir’s built-in JSON.Encoder.
  • If Jason is available, it also emits a Jason.Encoder implementation.
  • It only casts the top-level object into a struct right now. Nested objects remain maps.
  • Exonerate is used at compile time and is not a runtime dependency.

This came out of wanting a simple way to keep JSON Schema as the source of truth while still getting normal Elixir structs and helpers in application code.

Hex: auto_struct | Hex

Docs: AutoStruct v0.3.0 — Documentation

Repo:

6 Likes