Skip to content

How-ToGPU

How to Use Structured Outputs in Ollama: Get Reliable JSON From Local AI Models

How to get reliable JSON from local AI models with Ollama's structured outputs: request JSON, enforce a schema, use Pydantic in Python or Zod in JavaScript, extract data from text and images, and keep results consistent.

By , Systems & Technical Editor

3 min read

How to Use Structured Outputs in Ollama: Get Reliable JSON From Local AI Models

Ask a local AI model for "a list of components with prices" and you'll get a different format every time, which is no use if a script needs to read the answer. Ollama's structured outputs fix that by enforcing a JSON schema on the model's reply. It's ideal for pulling details out of text, tagging images or sorting files with a model running on your own graphics card. This guide follows Ollama's official documentation.

What you need

One limitation: Ollama's documentation says its cloud doesn't currently support structured outputs, so this is a feature for models running locally.

Option 1: Ask for any valid JSON

The simplest version sets format to "json". Using the REST API from a terminal:

curl -X POST http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "gpt-oss",
  "messages": [{"role": "user", "content": "Tell me about Canada in one line"}],
  "stream": false,
  "format": "json"
}'

This guarantees JSON, but not which fields you'll get. For anything a script depends on, use a schema.

Option 2: Enforce a JSON schema

Pass a JSON schema as the format value instead. This example, based on Ollama's documentation, requires a name, a capital and a list of languages:

"format": {
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "capital": {"type": "string"},
    "languages": {"type": "array", "items": {"type": "string"}}
  },
  "required": ["name", "capital", "languages"]
}

Ollama's documentation also recommends passing the schema as text in your prompt to ground the model's response.

In Python, with Pydantic

With the official ollama Python library and Pydantic, you define the shape as a class, pass its schema and validate the reply:

from ollama import chat
from pydantic import BaseModel

class Country(BaseModel):
    name: str
    capital: str
    languages: list[str]

response = chat(
    model='gpt-oss',
    messages=[{'role': 'user', 'content': 'Tell me about Canada.'}],
    format=Country.model_json_schema(),
)
country = Country.model_validate_json(response.message.content)
print(country)

New to the library? Our Ollama Python guide covers installation.

In JavaScript, with Zod

The JavaScript library works the same way with Zod. Ollama's example serialises the schema with z.toJSONSchema() and parses the reply:

import ollama from 'ollama'
import * as z from 'zod'

const Country = z.object({
  name: z.string(),
  capital: z.string(),
  languages: z.array(z.string()),
})

const response = await ollama.chat({
  model: 'gpt-oss',
  messages: [{ role: 'user', content: 'Tell me about Canada.' }],
  format: z.toJSONSchema(Country),
})
const country = Country.parse(JSON.parse(response.message.content))
console.log(country)

Practical example: extract data from text

Structured outputs shine when you need to pull details out of messy text. Ollama's documentation shows a list of pets being extracted from a sentence: you define a Pet class (name, animal, age, colour, favourite toy), wrap it in a PetList, and the model fills in the fields. In Ollama's example, fields that may be missing (colour and favourite toy) are marked optional with str | None.

The same approach works for PC-related jobs, such as turning a messy parts list into component, brand and model fields. Always check the extracted values: a schema guarantees the format, not the facts.

Structured outputs with images

Vision models accept the same format parameter. Ollama's example asks a vision model (gemma4) to describe a photo and return a summary, a list of detected objects with confidence values, colours, time of day and setting, using Literal types to restrict answers to fixed options such as Indoor or Outdoor. See how to use vision models in Ollama to get set up.

Tips for reliable results

Ollama's documentation suggests:

  • Define schemas with Pydantic or Zod so you can reuse them to validate the reply.

  • Lower the temperature, for example to 0, for more deterministic output (pass it in options).

  • Use the OpenAI-compatible API if you prefer: structured outputs work there through response_format. Our Ollama OpenAI API guide explains that endpoint.

Our verdict

If you're using local models in scripts, structured outputs are the feature that makes the results usable: define a schema with Pydantic or Zod, pass it as format, and validate what comes back. Keep the temperature low, put the schema in your prompt as well, and remember that valid JSON can still contain wrong answers, so check anything important.

The bottom line

If you're using local models in scripts, structured outputs are the feature that makes the results usable: define a schema with Pydantic or Zod, pass it as format, and validate what comes back. Keep the temperature low, put the schema in your prompt as well, and remember that valid JSON can still contain wrong answers, so check anything important.

About the author

Marcus Thorne

Systems & Technical Editor

Marcus writes Forge PC's step-by-step build, troubleshooting and system optimisation guides. His background spans Windows kernel and power-state diagnostics, UEFI/BIOS configuration, NVMe storage arrays, ATX 3.1 power delivery and running local AI and LLM workloads on consumer graphics cards.

More from Marcus Thorne

Read next

How to Fix a Mouse That Double-Clicks When You Click Once

How-To

How to Fix a Mouse That Double-Clicks When You Click Once

How to fix a mouse that double-clicks when you click once: check Windows' click and double-click speed settings, test in other apps, change USB port, clean the button and test on another PC, plus what to do if the mouse is faulty.

Marcus Thorne3 min

How to Use the Windows Backup App in Windows 11

How-To

How to Use the Windows Backup App in Windows 11

How to use the Windows Backup app in Windows 11 to save your folders to OneDrive and your apps, settings and Wi-Fi details to your Microsoft account, restore them on a new PC, change what's backed up and understand its limits.

Marcus Thorne3 min

How to Remove or Turn Off Copilot in Windows 11

How-To

How to Remove or Turn Off Copilot in Windows 11

How to remove or turn off Microsoft Copilot in Windows 11: uninstall the Copilot app in Settings or with PowerShell, change what the Copilot key does, and the AppLocker option Microsoft recommends for IT admins.

Marcus Thorne3 min

How to Translate Text Offline on Your PC with LibreTranslate

How-To

How to Translate Text Offline on Your PC with LibreTranslate

How to run LibreTranslate, a free and open-source translation service, on your own PC: install it with pip, load only the languages you need, translate in the browser or through its API, keep it local and add optional CUDA acceleration.

Marcus Thorne3 min