Examples

The code on this page is run when the documentation is built. The schemas are in the examples/ directory of the repository.

A product catalog

This schema is from the Getting Started Step-By-Step guide of the JSON Schema organization. It describes a product with a nested object and a few constraints:

schema = joinpath(EXAMPLES, "acme_schemas", "acme_nestedschema.json")
print(read(schema, String))
{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://example.com/product.schema.json",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
      "productId": {
        "description": "The unique identifier for a product",
        "type": "integer"
      },
      "productName": {
        "description": "Name of the product",
        "type": "string"
      },
      "price": {
        "description": "The price of the product",
        "type": "number",
        "exclusiveMinimum": 0
      },
      "tags": {
        "description": "Tags for the product",
        "type": "array",
        "items": {
          "type": "string"
        },
        "minItems": 1,
        "uniqueItems": true
      },
      "dimensions": {
        "description": "Dimensions of a product",
        "type": "object",
        "properties": {
          "length": {
            "type": "number"
          },
          "width": {
            "type": "number"
          },
          "height": {
            "type": "number"
          }
        },
        "required": [ "length", "width", "height" ]
      }
    },
    "required": [ "productId", "productName", "price" ]
  }

Generate a module from it, and load it:

file = generate_module(schema, joinpath(OUT, "ProductTypes.jl"))
include(file)
using .ProductTypes

These are the generated types (the rest of the file is the code for reading, writing and validating, the same in every generated module):

show_types(file)
# ---------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------
# Runtime support for validating values of the generated types against their schema.
#
# This code is copied verbatim into the modules generated by JSONSchema2Types, after the
# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the
# default), the constructors of the generated types call these checks; with
# `validation = :separate`, it is in a separate file, which provides `validate`.
# ---------------------------------------------------------------------------------------

# --- Turning the checks off (with `validation = :inline`) ---

"""
    checks!(flag::Bool)

Turn on or off the checks of the constraints of the schema when values of the generated
types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...).
They are on by default (unless the module was generated with `checks = false`).

With the checks off, values are only converted to the types of their fields, which still
enforce the structure of the schema (the types of the properties, required properties,
the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`,
the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later
with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the
checks are off. A JSON value read into a union of generated types (from `oneOf` or
`anyOf`) is still checked, to choose its type.

The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it
temporarily. Returns the previous setting.
"""
checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old)

"""
    checks() -> Bool

Whether the checks of the constraints of the schema are on; see [`checks!`](@ref).
"""
checks() = _CHECKS[]

"""
    with_checks(f, flag::Bool)

Call `f()` with the checks of the constraints of the schema turned on or off (see
[`checks!`](@ref)), and restore the previous setting afterwards:
`with_checks(false) do ... end`.
"""
function with_checks(f, flag::Bool)
    old = checks!(flag)
    try
        return f()
    finally
        _CHECKS[] = old
    end
end

# The metadata of the structs used by the checks, with their constraints: the same as
# `_specs` when the constructors check (`validation = :inline`); otherwise the validation
# file defines a method for each struct.
_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T)

# Where a value is in a document, for the messages of the errors: built only when a check
# fails, so that valid values cost no string allocations.
struct _JSField{T}
    key::String
end
Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`")
struct _JSItem{W}
    parent::W
    index::Int
end
Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]")

# --- Validation of constraints ---

_jslength(x::AbstractString) = length(x)

# values of typed formats (dates, UUIDs) are validated through their string form
_jsscalar(x) = x

# `nothing` is an absent optional field, unless `null` is a value (e.g. a JSON document `null`)
function _jsvalidate(x, c, where_; null_is_value::Bool = false)
    c === nothing && return nothing
    x === nothing && !null_is_value && return nothing
    x = _jsscalar(x)
    if haskey(c, :schema)
        err = _jsvalid(c.schema, x isa AbstractSchemaObject ? x : _jsto(x))
        err === nothing || _jsfail("$where_ is invalid: $err")
    end
    if x isa Real && !(x isa Bool)
        haskey(c, :minimum) && x < c.minimum && _jsfail("$where_ must be ≥ $(c.minimum), got $x")
        haskey(c, :maximum) && x > c.maximum && _jsfail("$where_ must be ≤ $(c.maximum), got $x")
        haskey(c, :exclusiveMinimum) && x <= c.exclusiveMinimum && _jsfail("$where_ must be > $(c.exclusiveMinimum), got $x")
        haskey(c, :exclusiveMaximum) && x >= c.exclusiveMaximum && _jsfail("$where_ must be < $(c.exclusiveMaximum), got $x")
        if haskey(c, :multipleOf)
            q = x / c.multipleOf
            isapprox(q, round(q); atol = 1e-9) || _jsfail("$where_ must be a multiple of $(c.multipleOf), got $x")
        end
    elseif x isa AbstractString
        haskey(c, :minLength) && _jslength(x) < c.minLength && _jsfail("$where_ must have at least $(c.minLength) characters, got $(repr(x))")
        haskey(c, :maxLength) && _jslength(x) > c.maxLength && _jsfail("$where_ must have at most $(c.maxLength) characters, got $(repr(x))")
        haskey(c, :pattern) && !occursin(c.pattern, x) && _jsfail("$where_ must match the pattern $(c.pattern.pattern), got $(repr(x))")
    elseif x isa AbstractVector
        haskey(c, :minItems) && length(x) < c.minItems && _jsfail("$where_ must have at least $(c.minItems) items, got $(length(x))")
        haskey(c, :maxItems) && length(x) > c.maxItems && _jsfail("$where_ must have at most $(c.maxItems) items, got $(length(x))")
        haskey(c, :uniqueItems) && c.uniqueItems && !_jsallunique(x) && _jsfail("$where_ must have unique items")
        if haskey(c, :items)
            for (i, el) in enumerate(x)
                _jsvalidate(el, c.items, _JSItem(where_, i))
            end
        end
    elseif x isa AbstractDict
        haskey(c, :minProperties) && length(x) < c.minProperties && _jsfail("$where_ must have at least $(c.minProperties) properties")
        haskey(c, :maxProperties) && length(x) > c.maxProperties && _jsfail("$where_ must have at most $(c.maxProperties) properties")
    end
    return nothing
end

"""
    _jscheck(T, values, extra)

Check the constraints of the generated struct `T` (recorded in [`_SPECS`](@ref)) on the
converted field `values` and the additional properties `extra`. Called by the inner
constructor of `T`, after [`_jsfrom`](@ref) converted each argument: it checks that
required fields are set, the constraints of each field (`minimum`, `pattern`,
`minItems`...), the subschemas checked at runtime (`not`, `oneOf`, `format`...) and the
constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...).
"""
function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject}
    _CHECKS[] || return nothing
    spec = _vspecs(T)
    nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values)
    spec.minProperties !== nothing && nprops < spec.minProperties &&
        _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops")
    spec.maxProperties !== nothing && nprops > spec.maxProperties &&
        _jsfail("`$(_jsname(T))` must have at most $(spec.maxProperties) properties set, got $nprops")
    if spec.schema !== nothing
        # keywords that apply to the object as a whole (`not`, `if`, `patternProperties`...)
        obj = JSON.Object{String, Any}()
        for (f, v) in zip(spec.fields, values)
            v === nothing && !(f.required && f.nullable) && continue
            obj[f.key] = _jsto(v)
        end
        extra === nothing || foreach(((k, v),) -> (obj[k] = _jsto(v)), extra)
        err = _jsvalid(spec.schema, obj)
        err === nothing || _jsfail("`$(_jsname(T))` is invalid: $err")
    end
    return nothing
end

# The checks of the fields, unrolled over the tuples of field metadata and values (the
# metadata is a constant, so this is type-stable); returns the number of properties set.
@inline _jscheckfields(::Type, ::Tuple{}, ::Tuple{}) = 0
@inline function _jscheckfields(::Type{T}, fields::Tuple, values::Tuple) where {T}
    f, v = first(fields), first(values)
    if v === nothing && f.required && !f.nullable
        _jsfail("required property `$(f.key)` of `$(_jsname(T))` cannot be `nothing`")
    end
    f.constraints === nothing || _jsvalidate(v, f.constraints, _JSField{T}(f.key))
    set = v !== nothing || (f.required && f.nullable)
    return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values))
end

function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum}
    _CHECKS[] || return value
    _jsenumok(T, value) || _jsfail(_jsenummsg(T, value))
    return value
end

# --- Validation of JSON values against (sub)schemas ---
#
# The generated types enforce most of a schema by themselves. The remaining keywords (`not`,
# `if`/`then`/`else`, exclusivity of `oneOf`, `patternProperties`, `format`, ...) are
# checked by validating the JSON form of a value against the corresponding subschemas,
# which the generator embeds (with their `$ref`s resolved) in the metadata of the types.

"""
    check_formats!(flag::Bool)

Enable or disable the validation of the `format` keyword. Enabled by default. The formats of
JSON Schema 2020-12 are checked (`date-time`, `date`, `time`, `duration`, `email`,
`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `iri`,
`iri-reference`, `uri-template`, `json-pointer`, `relative-json-pointer`, `uuid`, `regex`);
unknown formats are not.
"""
check_formats!(flag::Bool) = (_CHECK_FORMATS[] = flag)
const _CHECK_FORMATS = Ref(true)

const _REGEX_CACHE = Dict{String, Regex}()

# JSON Schema patterns are ECMAScript regular expressions. They are compiled with PCRE without
# Unicode classes (so `\d` and `\w` are ASCII, as in ECMAScript) and with `$` matching only at
# the end, after translating `\s` and long Unicode property names, which PCRE lacks.
const _JS_REGEX_OPTIONS = Base.PCRE.UTF | Base.PCRE.MATCH_INVALID_UTF | Base.PCRE.ALT_BSUX |
                          Base.PCRE.DOLLAR_ENDONLY
_jsregex(p::AbstractString) =
    get!(() -> Regex(_jsecmaregex(p), _JS_REGEX_OPTIONS, Base.DEFAULT_MATCH_OPTS), _REGEX_CACHE, p)

const _JS_SPACES = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff"
const _JS_PROPERTIES = Dict(
    "Letter" => "L", "Cased_Letter" => "LC", "Uppercase_Letter" => "Lu", "Lowercase_Letter" => "Ll",
    "Titlecase_Letter" => "Lt", "Modifier_Letter" => "Lm", "Other_Letter" => "Lo", "Mark" => "M",
    "Nonspacing_Mark" => "Mn", "Spacing_Mark" => "Mc", "Enclosing_Mark" => "Me", "Number" => "N",
    "Decimal_Number" => "Nd", "digit" => "Nd", "Letter_Number" => "Nl", "Other_Number" => "No",
    "Punctuation" => "P", "punct" => "P", "Connector_Punctuation" => "Pc", "Dash_Punctuation" => "Pd",
    "Open_Punctuation" => "Ps", "Close_Punctuation" => "Pe", "Initial_Punctuation" => "Pi",
    "Final_Punctuation" => "Pf", "Other_Punctuation" => "Po", "Symbol" => "S", "Math_Symbol" => "Sm",
    "Currency_Symbol" => "Sc", "Modifier_Symbol" => "Sk", "Other_Symbol" => "So", "Separator" => "Z",
    "Space_Separator" => "Zs", "Line_Separator" => "Zl", "Paragraph_Separator" => "Zp", "Other" => "C",
    "Control" => "Cc", "cntrl" => "Cc", "Format" => "Cf", "Surrogate" => "Cs", "Private_Use" => "Co",
    "Unassigned" => "Cn",
)

function _jsecmaregex(p::AbstractString)
    out = IOBuffer()
    inclass = false
    i = firstindex(p)
    while i <= lastindex(p)
        c = p[i]
        if c == '\\' && i < lastindex(p)
            n = p[nextind(p, i)]
            j = nextind(p, nextind(p, i))
            if n == 's'
                print(out, inclass ? _JS_SPACES : "[" * _JS_SPACES * "]")
            elseif n == 'S' && !inclass
                print(out, "[^", _JS_SPACES, "]")
            elseif (n == 'p' || n == 'P') && j <= lastindex(p) && p[j] == '{'
                k = findnext('}', p, j)
                k === nothing && (print(out, c, n); i = j; continue)
                name = replace(p[nextind(p, j):prevind(p, k)], r"^(General_Category|gc)=" => "")
                print(out, '\\', n, '{', get(_JS_PROPERTIES, name, name), '}')
                j = nextind(p, k)
            else
                print(out, c, n)
            end
            i = j
            continue
        end
        # `[]` matches nothing and `[^]` anything, in ECMAScript
        if !inclass && startswith(SubString(p, i), "[^]")
            print(out, "[\\s\\S]"); i = nextind(p, nextind(p, nextind(p, i))); continue
        elseif !inclass && startswith(SubString(p, i), "[]")
            print(out, "(?!)"); i = nextind(p, nextind(p, i)); continue
        end
        c == '[' && (inclass = true)
        c == ']' && (inclass = false)
        print(out, c)
        i = nextind(p, i)
    end
    return String(take!(out))
end

# --- Checks of the `format` keyword ---
#
# Following the RFCs referenced by JSON Schema; only ASCII digits are digits, and `\z` (not
# `$`, which allows a trailing newline) anchors the patterns.

_jsleap(y) = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)

function _jsdate(s)
    m = match(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})\z", s)
    m === nothing && return false
    y, mo, d = parse.(Int, m.captures)
    days = (31, _jsleap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    return 1 <= mo <= 12 && 1 <= d <= days[mo]
end

function _jstime(s)
    m = match(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|([+-])([0-9]{2}):([0-9]{2}))\z", s)
    m === nothing && return false
    h, mi, se = parse(Int, m[1]), parse(Int, m[2]), parse(Int, m[3])
    oh, om = m[6] === nothing ? (0, 0) : (parse(Int, m[7]), parse(Int, m[8]))
    (h <= 23 && mi <= 59 && se <= 60 && oh <= 23 && om <= 59) || return false
    if se == 60
        # a leap second is only at 23:59:60 UTC
        utc = mod(h * 60 + mi - (m[6] == "-" ? -1 : 1) * (oh * 60 + om), 24 * 60)
        utc == 23 * 60 + 59 || return false
    end
    return true
end

function _jsdatetime(s)
    m = match(r"^([^Tt]*)[Tt](.*)\z", s)
    return m !== nothing && _jsdate(m[1]) && _jstime(m[2])
end

function _jsipv4(s)
    m = match(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z", s)
    m === nothing && return false
    return all(c -> (length(c) == 1 || c[1] != '0') && parse(Int, c) <= 255, m.captures)
end

function _jsipv6(s)
    (isascii(s) && !isempty(s) && !occursin(r"[^0-9A-Fa-f:.]", s)) || return false
    parts = split(s, "::")
    length(parts) > 2 && return false
    groups(p) = isempty(p) ? String[] : split(p, ':')
    gs = vcat([groups(p) for p in parts]...)
    n = 0
    for (i, g) in enumerate(gs)
        if occursin('.', g)
            # an IPv4 address can only be the last group
            (i == length(gs) && last(parts) != "" && _jsipv4(g)) || return false
            n += 2
        else
            occursin(r"^[0-9A-Fa-f]{1,4}\z", g) || return false
            n += 1
        end
    end
    return length(parts) == 2 ? n <= 7 : n == 8
end

function _jshostname(s)
    isascii(s) || return false
    s = endswith(s, ".") && length(s) > 1 ? chop(s) : s
    (1 <= length(s) <= 253) || return false
    for label in split(s, '.')
        occursin(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\z", label) || return false
        # "--" in the 3rd and 4th positions is reserved (RFC 5891), except for "xn--" labels
        length(label) >= 4 && label[3:4] == "--" && lowercase(label[1:2]) != "xn" && return false
    end
    return true
end

# Internationalized hostnames: checked as hostnames, allowing non-ASCII letters; the
# IDNA2008 rules are not checked.
const _JS_IDN_DOTS = Regex("[\u3002\uFF0E\uFF61]")
const _JS_IDN_LABEL = Regex("^[\\p{L}\\p{N}\\p{M}\\-\u00B7\u0375\u05F3\u05F4\u30FB\u200C\u200D]+\\z")

function _jsidnhostname(s)
    s = replace(s, _JS_IDN_DOTS => ".")
    (1 <= length(s) <= 253) || return false
    occursin(Regex("[\\s\u302E]"), s) && return false
    for label in split(endswith(s, ".") && length(s) > 1 ? chop(s) : s, '.')
        (1 <= length(label) <= 63) || return false
        (startswith(label, "-") || endswith(label, "-")) && return false
        occursin(_JS_IDN_LABEL, label) || return false
        occursin(r"^\p{M}", label) && return false
    end
    return true
end

const _JS_ATEXT = raw"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]"

function _jsemail(s; idn = false)
    i = findlast('@', s)
    i === nothing && return false
    local_part, domain = s[1:prevind(s, i)], s[nextind(s, i):end]
    atext = idn ? raw"(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]|[^\x00-\x7F])" : _JS_ATEXT
    dotatom = Regex("^" * atext * "+(\\." * atext * "+)*\\z")
    quoted = idn ? r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|[^\x00-\x7F]|\\[\x20-\x7E])*\"\z" :
                   r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|\\[\x20-\x7E])*\"\z"
    (occursin(dotatom, local_part) || occursin(quoted, local_part)) || return false
    if startswith(domain, "[") && endswith(domain, "]")
        lit = domain[2:end-1]
        return startswith(lowercase(lit), "ipv6:") ? _jsipv6(lit[6:end]) : _jsipv4(lit)
    end
    endswith(domain, ".") && return false
    return idn ? _jsidnhostname(domain) : _jshostname(domain)
end

# URIs and IRIs (RFC 3986 and 3987): the characters, percent-encodings, scheme and authority
const _JS_URI_CHARS = raw"A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;="
function _jsuri(s; absolute = true, iri = false)
    chars = iri ? "[" * _JS_URI_CHARS * "\u00A0-\U10FFFF]" : "[" * _JS_URI_CHARS * "]"
    occursin(Regex("^(" * chars * "|%[0-9A-Fa-f]{2})*\\z"), s) || return false
    m = match(r"^(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?\z", s)
    m === nothing && return false
    absolute && m[1] === nothing && return false
    # without a scheme, a first path segment with ':' would be read as a scheme
    m[1] === nothing && m[2] === nothing && occursin(r"^[^/]*:", m[3]) && return false
    for part in (m[3], m[4], m[5])
        part === nothing || !occursin(r"[\[\]]", part) || return false
    end
    count('#', s) <= 1 || return false
    if m[2] !== nothing
        auth = m[2]
        hm = match(r"^(?:[^@\[\]]*@)?(\[[^\]]*\]|[^:\[\]@]*)(?::([0-9]*))?\z", auth)
        hm === nothing && return false
        if startswith(hm[1], "[")
            h = hm[1][2:end-1]
            (occursin(r"^[vV][0-9A-Fa-f]+\.", h) || _jsipv6(h)) || return false
        end
    end
    return true
end

_jsjsonpointer(s) = occursin(r"^(/([^~/]|~[01])*)*\z", s)
_jsreljsonpointer(s) = occursin(r"^(0|[1-9][0-9]*)(#|(/([^~/]|~[01])*)*)\z", s)

# RFC 6570: literals, and expressions `{[operator]varspec,...}`
const _JS_URI_TEMPLATE = Regex("^(?:[^\\x00-\\x20\"'%<>\\\\^`{|}\\x7F]|%[0-9A-Fa-f]{2}|" *
    "\\{[+#./;?&=,!@|]?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" *
    "(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" *
    "(?::[1-9][0-9]{0,3}|\\*)?)*\\})*\\z")
_jsuritemplate(s) = occursin(_JS_URI_TEMPLATE, s)

# RFC 3339, appendix A: "P" (date [time] / time / week), where e.g. years and days need months
const _JS_DURATION = let D = "[0-9]+",
        time = "T(?:$(D)H(?:$(D)M(?:$(D)S)?)?|$(D)M(?:$(D)S)?|$(D)S)",
        date = "(?:$(D)Y(?:$(D)M(?:$(D)D)?)?|$(D)M(?:$(D)D)?|$(D)D)"
    Regex("^P(?:$(date)(?:$(time))?|$(time)|$(D)W)\\z")
end
_jsduration(s) = occursin(_JS_DURATION, s)

_jsuuid(s) = occursin(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z", s)

function _jsregexformat(s)
    # syntax of PCRE (or Python) that ECMAScript does not have
    occursin(r"\(\?(P[<=>]|#|[a-zA-Z]+\))|\\a", s) && return false
    try
        _jsregex(s)
        return true
    catch
        # some ECMAScript forms are not supported by PCRE: accept what PCRE rejects only
        # for lookbehinds, which ECMAScript allows with variable width
        return occursin("(?<", s)
    end
end

const _FORMATS = Dict{String, Function}(
    "date-time" => _jsdatetime,
    "date" => _jsdate,
    "time" => _jstime,
    "duration" => _jsduration,
    "email" => _jsemail,
    "idn-email" => s -> _jsemail(s; idn = true),
    "hostname" => _jshostname,
    "idn-hostname" => _jsidnhostname,
    "ipv4" => _jsipv4,
    "ipv6" => _jsipv6,
    "uri" => _jsuri,
    "uri-reference" => s -> _jsuri(s; absolute = false),
    "iri" => s -> _jsuri(s; iri = true),
    "iri-reference" => s -> _jsuri(s; absolute = false, iri = true),
    "uri-template" => _jsuritemplate,
    "json-pointer" => _jsjsonpointer,
    "relative-json-pointer" => _jsreljsonpointer,
    "uuid" => _jsuuid,
    "regex" => _jsregexformat,
)

_jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x)

function _jstypeok(t::AbstractString, x)
    t == "null" && return x === nothing
    t == "boolean" && return x isa Bool
    t == "integer" && return _jsisinteger(x)
    t == "number" && return _jsisnumber(x)
    t == "string" && return x isa AbstractString
    t == "array" && return x isa AbstractVector
    t == "object" && return x isa AbstractDict
    return true
end

function _jsallunique(x)
    v = Any[_jsto(el) for el in x]
    return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1)
end

"""
    _jsvalid(schema, x) -> Union{Nothing, String}

Validate the JSON value `x` against `schema`; return `nothing` if it is valid, or a
message describing the first problem found.
"""
_jsvalid(s, x) = first(_jsvalidann(s, x))

# Annotations collected while validating: the properties and array items that were
# evaluated by a (sub)schema, for `unevaluatedProperties` and `unevaluatedItems`.
_jsok(props = Set{String}(), items = Set{Int}()) = (nothing, props, items)
_jsbad(msg) = (msg, Set{String}(), Set{Int}())

"""
    _jsvalidann(schema, x) -> (error, evaluated_properties, evaluated_items)

Validate `x` against `schema` as [`_jsvalid`](@ref), and also return the names of the
properties and the (1-based) indices of the items that the schema evaluated, as defined by
JSON Schema 2020-12 for `unevaluatedProperties` and `unevaluatedItems`.
"""
function _jsvalidann(s, x)
    s === true && return _jsok()
    s === false && return _jsbad("no value is allowed here")
    s isa AbstractDict || return _jsok()
    # A value of a generated type (from a field of a generated struct) is valid against
    # `{"\$type": "Name"}` when it is a value of that type. It is kept as it is through
    # `oneOf`, `anyOf` and `allOf`, and converted to its JSON form for anything else.
    if x isa AbstractSchemaObject
        if haskey(s, "\$type") && length(s) == 1
            x isa getfield(@__MODULE__, Symbol(s["\$type"])) && return _jsok(_jskeys(x))
            x = _jsto(x)
        elseif !all(in(("oneOf", "anyOf", "allOf")), keys(s))
            x = _jsto(x)
        end
    end
    props = Set{String}()
    items = Set{Int}()
    addann!(ann) = (union!(props, ann[2]); union!(items, ann[3]))

    if haskey(s, "\$type")
        # a generated type: the value must be convertible to it, which checks all of it
        T = getfield(@__MODULE__, Symbol(s["\$type"]))
        msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing
        msg === nothing || return _jsbad(msg)
        v = try
            _jsfrom(T, x)
        catch err
            err isa SchemaValidationError || rethrow()
            return _jsbad(err.msg)
        end
        # (constructors that do not check only convert: check the converted value)
        if !_INLINE_CHECKS
            errs = with_checks(() -> _jscollect!(String[], v, Any[]), true)
            isempty(errs) || return _jsbad(first(errs))
        end
        x isa AbstractDict && union!(props, String.(keys(x)))
        x isa AbstractVector && union!(items, eachindex(x))
    end

    if haskey(s, "type")
        ts = s["type"] isa AbstractVector ? s["type"] : (s["type"],)
        any(t -> _jstypeok(t, x), ts) || return _jsbad("expected $(join(ts, " or ")), got $(repr(x))")
    end
    haskey(s, "enum") && !any(v -> _jseq(v, x), s["enum"]) && return _jsbad("$(repr(x)) is not one of $(s["enum"])")
    haskey(s, "const") && !_jseq(s["const"], x) && return _jsbad("expected $(repr(s["const"])), got $(repr(x))")

    if _jsisnumber(x)
        haskey(s, "minimum") && x < s["minimum"] && return _jsbad("$x is less than $(s["minimum"])")
        haskey(s, "maximum") && x > s["maximum"] && return _jsbad("$x is greater than $(s["maximum"])")
        haskey(s, "exclusiveMinimum") && s["exclusiveMinimum"] isa Real && !(s["exclusiveMinimum"] isa Bool) &&
            x <= s["exclusiveMinimum"] && return _jsbad("$x is not greater than $(s["exclusiveMinimum"])")
        haskey(s, "exclusiveMaximum") && s["exclusiveMaximum"] isa Real && !(s["exclusiveMaximum"] isa Bool) &&
            x >= s["exclusiveMaximum"] && return _jsbad("$x is not less than $(s["exclusiveMaximum"])")
        if haskey(s, "multipleOf")
            q = x / s["multipleOf"]
            isapprox(q, round(q); atol = 1e-9) || return _jsbad("$x is not a multiple of $(s["multipleOf"])")
        end
    elseif x isa AbstractString
        haskey(s, "minLength") && length(x) < s["minLength"] && return _jsbad("$(repr(x)) is shorter than $(s["minLength"])")
        haskey(s, "maxLength") && length(x) > s["maxLength"] && return _jsbad("$(repr(x)) is longer than $(s["maxLength"])")
        haskey(s, "pattern") && !occursin(_jsregex(s["pattern"]), x) &&
            return _jsbad("$(repr(x)) does not match the pattern $(s["pattern"])")
        if haskey(s, "format") && _CHECK_FORMATS[]
            check = get(_FORMATS, s["format"], nothing)
            check === nothing || check(x) || return _jsbad("$(repr(x)) is not a valid $(s["format"])")
        end
    elseif x isa AbstractVector
        haskey(s, "minItems") && length(x) < s["minItems"] && return _jsbad("fewer than $(s["minItems"]) items")
        haskey(s, "maxItems") && length(x) > s["maxItems"] && return _jsbad("more than $(s["maxItems"]) items")
        if get(s, "uniqueItems", false) === true
            for i in eachindex(x), j in firstindex(x):i-1
                _jseq(x[i], x[j]) && return _jsbad("items are not unique")
            end
        end
        prefix = get(s, "prefixItems", get(s, "items", nothing) isa AbstractVector ? s["items"] : Any[])
        for (i, sub) in enumerate(prefix)
            i <= length(x) || break
            err = _jsvalid(sub, x[i])
            err === nothing || return _jsbad("item $i: $err")
            push!(items, i)
        end
        rest = haskey(s, "prefixItems") ? get(s, "items", nothing) :
               get(s, "items", nothing) isa AbstractVector ? get(s, "additionalItems", nothing) : get(s, "items", nothing)
        if rest !== nothing
            for i in (length(prefix) + 1):length(x)
                err = _jsvalid(rest, x[i])
                err === nothing || return _jsbad("item $i: $err")
                push!(items, i)
            end
        end
        if haskey(s, "contains")
            matching = [i for i in eachindex(x) if _jsvalid(s["contains"], x[i]) === nothing]
            n = length(matching)
            lo = get(s, "minContains", 1); hi = get(s, "maxContains", typemax(Int))
            lo <= n <= hi || return _jsbad("$n items match `contains`; expected between $lo and $hi")
            union!(items, matching)
        end
    elseif x isa AbstractDict
        haskey(s, "minProperties") && length(x) < s["minProperties"] && return _jsbad("fewer than $(s["minProperties"]) properties")
        haskey(s, "maxProperties") && length(x) > s["maxProperties"] && return _jsbad("more than $(s["maxProperties"]) properties")
        for k in get(s, "required", ())
            haskey(x, k) || return _jsbad("missing required property `$k`")
        end
        defined = get(s, "properties", nothing)
        patterns = get(s, "patternProperties", nothing)
        extra = get(s, "additionalProperties", nothing)
        names = get(s, "propertyNames", nothing)
        (defined === nothing && patterns === nothing && extra === nothing && names === nothing) ||
        for (k, v) in x
            k = String(k)
            matched = false
            if defined !== nothing && haskey(defined, k)
                matched = true
                err = _jsvalid(defined[k], v)
                err === nothing || return _jsbad("property `$k`: $err")
            end
            for (p, sub) in something(patterns, ())
                occursin(_jsregex(p), k) || continue
                matched = true
                err = _jsvalid(sub, v)
                err === nothing || return _jsbad("property `$k`: $err")
            end
            if !matched && extra !== nothing
                err = _jsvalid(extra, v)
                err === nothing || return _jsbad(extra === false ? "property `$k` is not allowed" : "property `$k`: $err")
                matched = true
            end
            matched && push!(props, k)
            if names !== nothing
                err = _jsvalid(names, k)
                err === nothing || return _jsbad("property name `$k`: $err")
            end
        end
        (haskey(s, "dependentRequired") || haskey(s, "dependencies")) &&
        for (k, deps) in merge(get(s, "dependentRequired", Dict()), filter(p -> p[2] isa AbstractVector, get(s, "dependencies", Dict())))
            haskey(x, k) || continue
            for d in deps
                haskey(x, d) || return _jsbad("property `$k` requires property `$d`")
            end
        end
        (haskey(s, "dependentSchemas") || haskey(s, "dependencies")) &&
        for (k, sub) in merge(get(s, "dependentSchemas", Dict()), filter(p -> !(p[2] isa AbstractVector), get(s, "dependencies", Dict())))
            haskey(x, k) || continue
            ann = _jsvalidann(sub, x)
            ann[1] === nothing || return _jsbad("when `$k` is present: $(ann[1])")
            addann!(ann)
        end
    end

    for sub in get(s, "allOf", ())
        ann = _jsvalidann(sub, x)
        ann[1] === nothing || return ann
        addann!(ann)
    end
    if haskey(s, "anyOf")
        anns = [_jsvalidann(sub, x) for sub in s["anyOf"]]
        valid = filter(a -> a[1] === nothing, anns)
        isempty(valid) && return _jsbad("does not match any option of `anyOf` (" * join(first.(anns), "; ") * ")")
        foreach(addann!, valid)
    end
    if haskey(s, "oneOf")
        valid = filter(a -> a[1] === nothing, [_jsvalidann(sub, x) for sub in s["oneOf"]])
        n = length(valid)
        n == 1 || return _jsbad(n == 0 ? "does not match any option of `oneOf`" :
                                         "matches $n options of `oneOf`, but must match exactly one")
        addann!(only(valid))
    end
    haskey(s, "not") && _jsvalid(s["not"], x) === nothing && return _jsbad("must not match the schema in `not`")
    if haskey(s, "if")
        cond = _jsvalidann(s["if"], x)
        if cond[1] === nothing
            addann!(cond)
            if haskey(s, "then")
                ann = _jsvalidann(s["then"], x)
                ann[1] === nothing || return _jsbad("`then`: " * ann[1])
                addann!(ann)
            end
        elseif haskey(s, "else")
            ann = _jsvalidann(s["else"], x)
            ann[1] === nothing || return _jsbad("`else`: " * ann[1])
            addann!(ann)
        end
    end

    # `unevaluatedItems` and `unevaluatedProperties` apply to what no other keyword of this
    # schema, or of its valid subschemas, evaluated
    if x isa AbstractVector && haskey(s, "unevaluatedItems")
        for i in eachindex(x)
            i in items && continue
            err = _jsvalid(s["unevaluatedItems"], x[i])
            err === nothing || return _jsbad(s["unevaluatedItems"] === false ? "item $i is not allowed" : "item $i: $err")
            push!(items, i)
        end
    end
    if x isa AbstractDict && haskey(s, "unevaluatedProperties")
        for (k, v) in x
            String(k) in props && continue
            err = _jsvalid(s["unevaluatedProperties"], v)
            err === nothing || return _jsbad(s["unevaluatedProperties"] === false ?
                                             "property `$k` is not allowed" : "property `$k`: $err")
            push!(props, String(k))
        end
    end
    return (nothing, props, items)
end

# the JSON names of the properties of a value of a generated type
function _jskeys(x::T) where {T <: AbstractSchemaObject}
    spec = _specs(T)
    ks = Set{String}()
    for f in spec.fields
        v = getfield(x, f.name)
        (v !== nothing || (f.required && f.nullable)) && push!(ks, f.key)
    end
    if spec.extra !== nothing
        union!(ks, keys(getfield(x, spec.extra)))
    end
    return ks
end

# --- Validation of whole values ---

"""
    violations(x) -> Vector{String}

Check `x` (a value of a generated type, or a vector, dict or tuple of them), and every
value nested in it, against all the constraints of the schema, whether or not the checks
were on when they were created (see [`checks!`](@ref)). Returns the problems found, one per
invalid value (the first problem of each), with its location, e.g.
`"batch_size: `value` in `VolumeType` must be ≥ 0, got -1.0"`. The location uses the JSON
names of the properties and 1-based indices of the items: `recipes[1].batch_size`.
"""
function violations(x)
    out = String[]
    with_checks(true) do
        _jscollect!(out, x, Any[])
        if x isa RootType && _ROOT_CONSTRAINTS[] !== nothing
            try
                _jsvalidate(x, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true)
            catch err
                err isa SchemaValidationError || rethrow()
                push!(out, err.msg)
            end
        end
    end
    return out
end

"""
    validate(x)

Check `x` as [`violations`](@ref) does, and throw a [`SchemaValidationError`](@ref) listing
the problems found, if any. Returns `x`.
"""
validate(x) = _jsvalidateall(x)

function _jsvalidateall(x)
    v = violations(x)
    isempty(v) && return x
    n = length(v)
    _jsfail("$n value$(n == 1 ? " does" : "s do") not conform to the schema:\n  " * join(v, "\n  "))
end

"""
    isvalid(x::AbstractSchemaObject) -> Bool

Whether `x`, and every value nested in it, conforms to the schema; see [`violations`](@ref).
"""
Base.isvalid(x::Union{AbstractSchemaObject, AbstractSchemaEnum}) = isempty(violations(x))

# The location of a value is kept as a stack of property names and indices, and only
# written out (e.g. `recipes[1].batch_size`) when a problem is found.
function _jsat(path::Vector{Any}, msg)
    isempty(path) && return msg
    io = IOBuffer()
    for (i, p) in enumerate(path)
        p isa Integer ? print(io, "[", p, "]") : print(io, i == 1 ? "" : ".", p)
    end
    return String(take!(io)) * ": " * msg
end

function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject}
    spec = _vspecs(T)
    values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields)))
    extra = spec.extra === nothing ? nothing : getfield(x, spec.extra)
    try
        _jscheck(T, values, extra)
    catch err
        err isa SchemaValidationError || rethrow()
        push!(out, _jsat(path, err.msg))
    end
    _jscollectfields!(out, spec.fields, values, path)
    extra === nothing || _jscollect!(out, extra, path)
    return out
end

# (unrolled over the tuples of field metadata and values, as `_jscheckfields`)
@inline _jscollectfields!(out, ::Tuple{}, ::Tuple{}, path) = out
@inline function _jscollectfields!(out, fields::Tuple, values::Tuple, path)
    v = first(values)
    if v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict}
        push!(path, first(fields).key)
        _jscollect!(out, v, path)
        pop!(path)
    end
    return _jscollectfields!(out, Base.tail(fields), Base.tail(values), path)
end

function _jscollect!(out, x::T, path) where {T <: AbstractSchemaEnum}
    _jsenumok(T, x.value) || push!(out, _jsat(path, _jsenummsg(T, x.value)))
    return out
end
function _jscollect!(out, x::Union{AbstractVector, Tuple}, path)
    for (i, v) in enumerate(x)
        v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue
        push!(path, i)
        _jscollect!(out, v, path)
        pop!(path)
    end
    return out
end
function _jscollect!(out, x::AbstractDict, path)
    for (k, v) in x
        v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue
        push!(path, String(k))
        _jscollect!(out, v, path)
        pop!(path)
    end
    return out
end
_jscollect!(out, x, path) = out

# the validation of values before writing them (see `tojson`)
_VALIDATOR[] = _jsvalidateall

# ---------------------------------------------------------------------------------------
# Types from `acme_nestedschema.json`
# ---------------------------------------------------------------------------------------

"""
    ProductDimensions(; kwargs...)
    ProductDimensions{I, T}(; kwargs...)

Dimensions of a product

Integers are stored as `I <: Integer` and other numbers as `T <: Real`; by default, `Int64`
and `Float64`.

# Fields

- `length::T` (required)
- `width::T` (required)
- `height::T` (required)
- `_extra::Dict{String, Any}`: additional properties, not described in the schema
"""
struct ProductDimensions{I <: Integer, T <: Real} <: AbstractSchemaObject
    length::T
    width::T
    height::T
    _extra::Dict{String, Any}
    function ProductDimensions{I, T}(; length, width, height, _extra = Dict{String, Any}()) where {I <: Integer, T <: Real}
        length = _jsfrom(T, length)
        width = _jsfrom(T, width)
        height = _jsfrom(T, height)
        _extra = _jsfrom(Dict{String, Any}, _extra)
        _jscheck(ProductDimensions{I, T}, (length, width, height), _extra)
        return new(length, width, height, _extra)
    end
end
ProductDimensions(; kwargs...) = ProductDimensions{Int64, Float64}(; kwargs...)
ProductDimensions{I, T}(length, width, height, _extra) where {I <: Integer, T <: Real} = ProductDimensions{I, T}(; length, width, height, _extra)
ProductDimensions(length, width, height, _extra) = ProductDimensions{_jsnumbertypes(length, width, height, _extra)...}(; length, width, height, _extra)
const _SPEC_ProductDimensions = (
    fields = (
        (name = :length, key = "length", required = true, nullable = false, constraints = nothing),
        (name = :width, key = "width", required = true, nullable = false, constraints = nothing),
        (name = :height, key = "height", required = true, nullable = false, constraints = nothing),
    ),
    additionalProperties = true,
    extra = :_extra,
    minProperties = nothing,
    maxProperties = nothing,
    schema = nothing,
)
_specs(::Type{<:ProductDimensions}) = _SPEC_ProductDimensions
_SPECS[ProductDimensions] = _SPEC_ProductDimensions

"""
    Product(; kwargs...)
    Product{I, T}(; kwargs...)

A product from Acme's catalog

Integers are stored as `I <: Integer` and other numbers as `T <: Real`; by default, `Int64`
and `Float64`.

# Fields

- `productId::I` (required): The unique identifier for a product
- `productName::String` (required): Name of the product
- `price::T` (required): The price of the product
- `tags::Union{Nothing, Vector{String}}`: Tags for the product
- `dimensions::Union{Nothing, ProductDimensions{I, T}}`: Dimensions of a product
- `_extra::Dict{String, Any}`: additional properties, not described in the schema
"""
struct Product{I <: Integer, T <: Real} <: AbstractSchemaObject
    productId::I
    productName::String
    price::T
    tags::Union{Nothing, Vector{String}}
    dimensions::Union{Nothing, ProductDimensions{I, T}}
    _extra::Dict{String, Any}
    function Product{I, T}(; productId, productName, price, tags = nothing, dimensions = nothing, _extra = Dict{String, Any}()) where {I <: Integer, T <: Real}
        productId = _jsfrom(I, productId)
        productName = _jsfrom(String, productName)
        price = _jsfrom(T, price)
        tags = _jsfrom(Union{Nothing, Vector{String}}, tags)
        dimensions = _jsfrom(Union{Nothing, ProductDimensions{I, T}}, dimensions)
        _extra = _jsfrom(Dict{String, Any}, _extra)
        _jscheck(Product{I, T}, (productId, productName, price, tags, dimensions), _extra)
        return new(productId, productName, price, tags, dimensions, _extra)
    end
end
Product(; kwargs...) = Product{Int64, Float64}(; kwargs...)
Product{I, T}(productId, productName, price, tags, dimensions, _extra) where {I <: Integer, T <: Real} = Product{I, T}(; productId, productName, price, tags, dimensions, _extra)
Product(productId, productName, price, tags, dimensions, _extra) = Product{_jsnumbertypes(productId, productName, price, tags, dimensions, _extra)...}(; productId, productName, price, tags, dimensions, _extra)
const _SPEC_Product = (
    fields = (
        (name = :productId, key = "productId", required = true, nullable = false, constraints = nothing),
        (name = :productName, key = "productName", required = true, nullable = false, constraints = nothing),
        (name = :price, key = "price", required = true, nullable = false, constraints = (exclusiveMinimum = 0,)),
        (name = :tags, key = "tags", required = false, nullable = false, constraints = (minItems = 1, uniqueItems = true,)),
        (name = :dimensions, key = "dimensions", required = false, nullable = false, constraints = nothing),
    ),
    additionalProperties = true,
    extra = :_extra,
    minProperties = nothing,
    maxProperties = nothing,
    schema = nothing,
)
_specs(::Type{<:Product}) = _SPEC_Product
_SPECS[Product] = _SPEC_Product


"""
    RootType

Alias of `Product`, the type of the root of the schema.
"""
const RootType = Product

end # module ProductTypes

Values are built with keyword constructors. Plain values are converted, and optional fields can be left out:

p = Product(productId = 1, productName = "An ice sculpture", price = 12.5,
            dimensions = Dict("length" => 7, "width" => 12, "height" => 9.5))
Product(1, "An ice sculpture", 12.5, nothing, ProductDimensions(7.0, 12.0, 9.5, Dict{String, Any}()), Dict{String, Any}())
p.dimensions
ProductDimensions(7.0, 12.0, 9.5, Dict{String, Any}())

and are written as JSON, without the fields that are not set:

print(tojson(p; pretty = true))
{
  "productId": 1,
  "productName": "An ice sculpture",
  "price": 12.5,
  "dimensions": {
    "length": 7,
    "width": 12,
    "height": 9.5
  }
}

Reading a document validates it against the schema:

json = """{"productId": 1, "productName": "An ice sculpture", "price": 0}"""
try
    fromjson(Product, json)
catch err
    showerror(stdout, err)
end
SchemaValidationError: `price` in `Product` must be > 0, got 0.0
json = """{"productId": 1, "productName": "Ice", "price": 1, "tags": ["cold", "cold"]}"""
try
    fromjson(Product, json)
catch err
    showerror(stdout, err)
end
SchemaValidationError: `tags` in `Product` must have unique items

A schema referenced by its $id

Another version of the product schema refers to a separate schema for the location of the warehouse by its $id, https://example.com/geographical-location.schema.json. The file with that schema is given with the schemas keyword:

file = generate_module(joinpath(EXAMPLES, "acme_schemas", "acme_withreferenceschema.json"),
    joinpath(OUT, "WarehouseTypes.jl"); module_name = "WarehouseTypes",
    schemas = [joinpath(EXAMPLES, "acme_schemas", "acme_tobereferredschema.json")])
include(file)
using .WarehouseTypes: Product as WarehouseProduct, LongitudeAndLatitude
data = joinpath(EXAMPLES, "acme_schemas", "acme_data.json")
print(read(data, String))
{
    "productId": 1,
    "productName": "An ice sculpture",
    "price": 12.50,
    "tags": [ "cold", "ice" ],
    "dimensions": {
        "length": 7.0,
        "width": 12.0,
        "height": 9.5
    },
    "warehouseLocation": {
        "latitude": -78.75,
        "longitude": 20.4
    }
}
product = WarehouseTypes.readjson(WarehouseProduct, data)
product.warehouseLocation
LongitudeAndLatitude(-78.75, 20.4, Dict{String, Any}())

The referenced schema has the title "Longitude and Latitude", which gives the name of its type, LongitudeAndLatitude.

oneOf, anyOf, allOf and not

This schema shows the keywords for combining schemas:

schema = joinpath(EXAMPLES, "more_schemas", "combined_schema.json")
print(read(schema, String))
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "CombinedSchemaExample",
  "description": "A single schema demonstrating oneOf, anyOf, allOf, and not.",
  "type": "object",
  "properties": {
    "one_of_user": {
      "description": "Demonstrates 'oneOf' for a user that is either a Person or a Company.",
      "oneOf": [
        {
          "title": "Person",
          "type": "object",
          "properties": {
            "user_type": {
              "type": "string",
              "const": "person"
            },
            "first_name": {
              "type": "string"
            },
            "last_name": {
              "type": "string"
            }
          },
          "required": ["user_type", "first_name", "last_name"]
        },
        {
          "title": "Company",
          "type": "object",
          "properties": {
            "user_type": {
              "type": "string",
              "const": "company"
            },
            "company_name": {
              "type": "string"
            }
          },
          "required": ["user_type", "company_name"]
        }
      ]
    },
    "any_of_identifier": {
      "description": "Demonstrates 'anyOf' for a product identifier.",
      "anyOf": [
        {
          "type": "object",
          "properties": {
            "sku": {
              "type": "string"
            }
          },
          "required": ["sku"]
        },
        {
          "type": "object",
          "properties": {
            "product_code": {
              "type": "string"
            }
          },
          "required": ["product_code"]
        }
      ]
    },
    "all_of_request": {
      "description": "Demonstrates 'allOf' to combine schemas for a request with authentication.",
      "allOf": [
        {
          "type": "object",
          "properties": {
            "payload": {
              "type": "object"
            }
          },
          "required": ["payload"]
        },
        {
          "type": "object",
          "properties": {
            "api_key": {
              "type": "string"
            },
            "timestamp": {
              "type": "string"
            }
          },
          "required": ["api_key", "timestamp"]
        }
      ]
    },
    "not_a_password": {
      "description": "A password that cannot be the literal string 'password'.",
      "type": "string",
      "not": {
        "const": "password"
      }
    }
  },
  "required": [
    "one_of_user",
    "any_of_identifier",
    "all_of_request",
    "not_a_password"
  ]
}
file = generate_module(schema, joinpath(OUT, "CombinedTypes.jl"); module_name = "CombinedTypes")
include(file)
using .CombinedTypes
fieldtypes(CombinedSchemaExample{Int64, Float64})
(Union{Main.CombinedTypes.Company{Int64, Float64}, Main.CombinedTypes.Person{Int64, Float64}}, Union{Main.CombinedTypes.CombinedSchemaExampleAnyOfIdentifierOption1{Int64, Float64}, Main.CombinedTypes.CombinedSchemaExampleAnyOfIdentifierOption2{Int64, Float64}}, Main.CombinedTypes.CombinedSchemaExampleAllOfRequest{Int64, Float64}, String, Dict{String, Any})

The options of oneOf have titles, so they are the types Person and Company. The options of anyOf have none, so their names are made from the parent and the property. The allOf is merged into a single type, and the not is checked at runtime. When reading, the option that fits is chosen:

json = """
{
  "one_of_user": {"user_type": "company", "company_name": "Acme"},
  "any_of_identifier": {"sku": "A-1"},
  "all_of_request": {"payload": {}, "api_key": "k", "timestamp": "2026-11-13"},
  "not_a_password": "s3cret"
}
"""
x = fromjson(RootType, json)
x.one_of_user
Company(CompanyUserTypeEnum("company"), "Acme", Dict{String, Any}())

and the not is enforced:

try
    fromjson(RootType, replace(json, "s3cret" => "password"))
catch err
    showerror(stdout, err)
end
SchemaValidationError: `not_a_password` in `CombinedSchemaExample` is invalid: must not match the schema in `not`