Course contents · Lesson 4 of 16

Get Structured JSON Output from an LLM, Hands-On

Structured Output and Tools · Lesson 4 of 16 · 11 min Hands-on

A support inbox gets dozens of emails a day, and you want a program to sort them: who wrote, when the problem happened, how urgent it is. An LLM can read the emails, but if it answers in sentences, your code still has to dig the facts out. This lesson shows how to get structured JSON output from a local model with Ollama, so every reply arrives as the same named fields, and how to check it before your code trusts it.

Letter versus form: why code needs named fields

In lesson 3 the replies were free text for a person to read. Code is a much worse reader. Ask "who wrote this, and how urgent is it?" and one reply says "The sender is Priya Sharma and it sounds urgent", the next puts the name last, and your code needs fragile string searches to find the facts.

Structured output means the model fills in named fields instead, in JSON, the text format of keys and values that the API itself uses. Then data["priority"] gives you the priority, every time. In the before-and-after, notice that every fact was already in the email: the form only gives each one a fixed place.

Before and after. Left, a support email in free text: subject Charged twice for order 4821, On 28 November 2026 I was charged twice, This is urgent, signed Priya Sharma, with the date, the word urgent and the name highlighted. Middle, an LLM given a schema. Right, a JSON object with name Priya Sharma, date 2026-11-28 and priority high, which code reads by key: the priority key gives high. Notes: with free text, code must guess where each fact is; with the form, the field names are the same every time.
The facts were in the email all along; the form gives each one a fixed, named place.

The easy way: format "json"

The first idea is to write "reply in JSON" in the prompt. It often works, and that is the trap. A small model sometimes wraps the JSON in a Markdown code fence or puts "Here is the JSON:" in front, and then json.loads, Python's JSON parser, fails. As with system prompts, a prompt is a request the model usually follows, not a rule.

So /api/chat takes a format field. Set it to "json" and the reply in message.content is a JSON object. The rest is the request from lesson 2:

payload = {
    "model": "llama3.2:3b",
    "messages": messages,
    "stream": False,
    "format": "json",
    "options": {"temperature": 0},
}

Two catches. Still describe the JSON you want in the prompt: Ollama's API docs warn that otherwise the model may write large amounts of whitespace. And "json" fixes only the syntax. The model still picks the keys, so you may get customer instead of name, or the date as "last Friday". The tips below explain temperature.

The better way: a JSON schema in format

A JSON schema is a JSON document that describes other JSON: which properties, or fields, an object has, the type of each, and which are required. An enum lists the only values allowed. It is the blank form, and the lab keeps it in schema.json.

Left, schema.json with descriptions trimmed: type object; properties, labelled the boxes; name with type string, labelled what goes in; date with type string and format date; priority with type string and an enum of low, medium and high, labelled allowed values; and a required list of name, date and priority, labelled must be filled. Right, an object that fits, with name Priya Sharma, date 2026-11-28 and priority high, each ticked. Below it, a line that does not fit: priority urgent, which is not in the enum. Note: a valid shape can still hold wrong values.
The schema fixes the shape, so "urgent" cannot appear, but it cannot tell whether the name or the date is true.

Put the schema itself, as a dictionary, in format instead of "json". Ollama turns it into a grammar: rules for what may come next. The model writes one token, a word piece, at a time, and any token that would break the rules is ruled out. So the reply has the keys you listed, a date shaped like 2026-11-28 and a priority from the enum. This is called constrained decoding.

The aha of the diagram: the schema checks shape, not truth. "urgent" cannot appear, but a wrong name or date can. Two details from the docs. Ollama's structured outputs page advises also pasting the schema into the prompt as text, so the model knows what each field means; the lab does. And Ollama hands the schema to llama.cpp, whose converter supports only part of JSON Schema and, as its grammar docs say, skips unsupported features silently.

Extract a support ticket, then validate anyway

The lab's task: read a support email and return a name, a date and a priority. On the Python side, pydantic, a library that checks data against Python type hints, defines the typed result:

class Ticket(BaseModel):
    name: str
    date: datetime.date
    priority: Literal["low", "medium", "high"]

Why check a reply that Ollama already constrained? It can be cut off at a token limit, a skipped schema keyword enforces nothing, and schema.json can drift away from the class. Validation means checking data against rules before you use it. check() in extract.py takes two steps: json.loads for the syntax, then Ticket.model_validate for fields and types, which also turns "2026-11-28" into a real datetime.date.

When the check fails, the script retries once. It appends the bad reply and a user message with the exact error, such as priority: Input should be 'low', 'medium' or 'high', so the model knows what to fix. In the flowchart, notice that the loop has an exit: after the second failure the script stops with a clear error instead of trying forever.

Flowchart. Prompt plus schema, sent with format schema, goes to the Ollama model at temperature 0, which returns JSON text in message.content. The app parses and checks it with json.loads and the Ticket class. Valid? Yes: use the Ticket, typed values for code. No: first attempt? Yes: retry once, sending the error back to the model. No: stop with a clear error after the second failure. A side card lists what the check catches: text that is not JSON, a missing field, a wrong type, a value not allowed. At most 2 attempts: first try plus one retry.
Every reply is checked; one retry carries the error message, and a second failure stops the script.

To run it, with Ollama from lesson 1 running and the labs cloned:

cd course-labs/building-llm-apps/04-structured-json
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 extract.py samples/email1.txt

This creates and activates a virtual environment, installs requests and pydantic, and extracts the first sample. pip should end with Successfully installed and a list that includes pydantic-2.14.4. Then the script prints the raw reply and the typed result (spacing and the model's judgement can differ):

Reading samples/email1.txt with llama3.2:3b, format: schema
attempt 1: model replied: {"name": "Priya Sharma", "date": "2026-11-28", "priority": "high"}
attempt 1: valid
Ticket(name='Priya Sharma', date=datetime.date(2026, 11, 28), priority='high')

The last line is a Python object, not text: its date.year is the number 2026. cannot connect to Ollama means the container is stopped, and No module named 'pydantic' means the environment is not active or the install was skipped.

Tips: temperature 0, small schemas, wrong values

Use temperature 0 for extraction. Temperature sets how much randomness goes into picking each next token. You want the likeliest reading of the email, not variety, and Ollama's docs suggest 0 for more deterministic output, so extract.py sends "options": {"temperature": 0}. The same email then usually gives the same JSON.

Keep schemas small. Every field is one more thing a small model can get wrong, the schema in the prompt costs tokens, and plain types stay inside what the converter supports. Split a big job into several small calls.

Valid JSON can still be wrong. samples/email2.txt says only "since last Tuesday", yet the schema requires a date, so the model has to write one: a guess in perfect YYYY-MM-DD shape. If a fact may be missing, allow null (in pydantic, datetime.date | None) and decide in code. Check values that matter against the source; lesson 10 does this for citations, and lesson 5 reuses schemas for tool arguments.

Check yourself

Your prompt says "reply only with JSON" and it worked in ten tests. Why set format anyway?

A prompt is a request, not a rule: the eleventh reply may arrive in a code fence or after a sentence, and json.loads fails. format makes Ollama enforce the output instead of hoping.

With a schema in format, Ollama constrains the reply. Why validate it at all?

The constraint covers only what you sent and what the converter supports. A reply cut off at a token limit, a silently skipped keyword or a schema that drifted from your class still gives data your code cannot use, and validation catches it first.

email2.txt returns a valid Ticket with a neat date, but the email only says "since last Tuesday". What went wrong?

Nothing in the format: the schema required a date, so the model had to write one, and it guessed. Allow null for facts that may be missing, and check important values against the source.