lean4-json-schema: JSON Schema with Machine-Checked Correctness in Lean 4

When you use an LLM with structured output, you hand it a JSON Schema and trust that whatever it returns actually conforms to it. On the other side, when your application serializes data to JSON, you trust that the serialization matches whatever schema you documented. These are both reasonable assumptions, right up until they're wrong and you're debugging a production incident at 2 AM because a field was null when it shouldn't have been.

We wanted something stronger. We wanted a system where you define a type, derive a JSON Schema from it, and get a machine-checked proof that every value of that type serializes to JSON that validates against its own schema. Not a test suite that checks a handful of examples, but a guarantee that covers every possible value, including the ones you didn't think of.

That's what lean4-json-schema aims to do.

What it is

lean4-json-schema is a Lean 4 library that gives you three things: a JSONSchema type strives to mirror the JSON Schema specification, a total validateJson function for runtime validation of JSON values against a given schema, and deriving handlers that automatically generate both schemas and correctness proofs for your Lean types.

Here's what it looks like in practice:

import JsonSchema

structure Person where
  name : String
  age : Nat
  deriving HasJSONSchema, ToJson, ValidatesAgainstSchema

That last line, ValidatesAgainstSchema, is where it gets interesting. It's not a runtime check. It's a compile-time proof obligation that Lean's kernel verifies. The derived instance proves this theorem for every possible Person value:

class ValidatesAgainstSchema (α : Type) [HasJSONSchema α] [ToJson α] : Prop where
  valid : ∀ (a : α), validateJson (HasJSONSchema.toSchema (α := α)) (toJson a) = .ok ()

In plain terms: for any a of type α, serializing a to JSON with toJson and then validating that JSON against the derived schema will always succeed. If your type definition and your ToJson instance don't actually agree with the schema, the proof won't go through and your code won't compile.

Note that this guarantee is unidirectional: the JSON value generated can always be validated against its schema, but not every possible JSON value that validates against the schema will necessarily deserialize back into the Lean type. For instance, Lean's Nat maps to a {"type": "integer"} schema, which also admits negative numbers. The schema is a sound over-approximation of what your type can produce, not an exact characterization. If you're consuming JSON (e.g. from LLM structured output), you should still handle deserialization errors.

The deriving handlers work across a wide range of type shapes. Enums become string schemas with enum constraints. Structures become object schemas with typed properties and required fields. Inductive types with mixed constructors become oneOf schemas. Recursive types like expression trees get proper $defs/$ref handling. Polymorphic types work too, generating parameterized instances that compose with whatever concrete type you plug in. Here is an example:

inductive TreeOf (α : Type) where
  | leaf : α → TreeOf α
  | node : TreeOf α → TreeOf α → TreeOf α
  deriving HasJSONSchema, ToJson, ValidatesAgainstSchema

When instantiated as TreeOf Nat, the derived HasJSONSchema instance produces the following JSON Schema:

{ "$defs": {
    "TreeOf": { "oneOf": [
      { "additionalProperties": false,
        "properties": { "leaf": { "type": "integer" } },
        "required": ["leaf"], "type": "object" },
      { "additionalProperties": false,
        "properties": { "node": {
          "prefixItems": [
            { "$ref": "#/$defs/TreeOf" },
            { "$ref": "#/$defs/TreeOf" }],
          "type": "array" }},
        "required": ["node"], "type": "object" }
    ]}},
  "$ref": "#/$defs/TreeOf" }

Why we built it

At Predictable Machines, we're building tools where correctness of serialization actually matters. For example, when you're trying to generate LLM responses as structured output, you need a JSON Schema for every kind of structured output you want the model to return. Writing those schemas by hand is tedious and error-prone. We wanted to easily derive schemas directly from Lean types and have the compiler verify that serialization always produces valid output against them.

We made it a standalone library because the problem is general. Anyone working with JSON in Lean 4 can use it, whether they care about LLMs or not. If you're building an API, a configuration system, or anything that touches JSON serialization, the same guarantees apply.

Getting started

Head over to the lean4-json-schema GitHub repo for up to date installation and usage instructions.

What's next

The library doesn't yet cover the full JSON Schema specification. We're adding features as we need them for our own work, but we'd welcome contributions that expand coverage.

If you're working in Lean 4 and care about JSON interop, give it a try. If you're interested in formal verification but haven't touched Lean yet, the codebase is a reasonable example of what applied theorem proving looks like in practice: not abstract mathematics, but concrete proofs about real serialization code. Issues and PRs are welcome on GitHub.

At Predictable Machines, we believe the tools we use to build correct software should themselves be correct. lean4-json-schema is one more step toward that goal, and part of a growing collection of libraries we're releasing. To stay up to date with all our open-source projects, visit our Open Source page.

Want to learn how we use Lean 4 and formal verification to prove your code is correct? Learn more about Predictable Code.

What we're building

Predictable Code gives every developer and AI assistant the same shared specifications so the code generated is consistent, verified, and always aligned with what your team intended.

Join the beta

Series

This article is part of our ongoing series on the hidden problems with AI code assistants in engineering teams.

Read the AI Code Pain Points →

More Articles

All articles

/ Curious to see our products in action? \

Let's have a chat about it

Predictable Code