Struct2JSONSchema.jl is a Julia package that converts Julia structs into JSON Schema documents compliant with JSON Schema draft 2020-12.
- Non-invasive: Generate JSON Schema without modifying existing struct definitions.
- Extensibility: Allow customization of schema generation for user-defined types and constraints.
- Robustness: Never raises an error; unrepresentable types are conservatively handled as
Any. - Long-term maintainability: Simple implementation with minimal dependencies.
For the design principles behind this package, see https://abap34.github.io/Struct2JSONSchema.jl/dev/#Concepts
using Struct2JSONSchema
using JSON
struct User
id::Int
name::String
email::Union{String, Nothing}
end
doc, unknowns = generate_schema(User)
println(JSON.json(doc, 4))
# {
# "$schema": "https://json-schema.org/draft/2020-12/schema",
# "$ref": "#/$defs/User__2fe39a6325a38198",
# ...We provide both a hook mechanism for expressive schema generation and a set of utility functions designed to make common customizations straightforward.
This allows users to define desirable constraints and formats for any type definition.
using UUIDs
using JSON
struct User
id::UUID
name::String
end
ctx = SchemaContext()
# Hooking into the generation process
register_override!(ctx) do ctx
if ctx.current_parent == User && ctx.current_field == :id
return Dict("type" => "string", "format" => "uuid")
else
return nothing
end
endThe same behavior can be expressed more concisely using a utility function:
struct User
id::Int
email::String
end
ctx = SchemaContext()
# Using a convenience utility function
register_field_override!(ctx, User, :email) do ctx
Dict("type" => "string", "format" => "email")
endAdditional utilities are provided for tasks such as:
- Marking specific fields as optional.
- Treating
Union{T, Nothing}andUnion{T, Missing}as optional fields. - Registering custom expansion strategies for abstract types.
For detailed customization options, see https://abap34.github.io/Struct2JSONSchema.jl/dev/#Customization
See the examples directory for additional usage examples.