Skip to content

How to Get JSON Output From llama.cpp (2026): JSON Schema, response_format and GBNF

7–10 minutes
Woman in a brick-walled loft holding a tablet with a JSON OUTPUT card, hook perfect JSON every time

Local models are great until you need a reply your code can parse.

Ask for JSON and you often get a friendly sentence, a markdown fence or a missing bracket. llama.cpp solves this at the sampling level: it can force the model to produce output that matches a JSON schema or a custom grammar, token by token.

This guide shows every way to get guaranteed JSON from llama.cpp. You will use response_format in the OpenAI-compatible API, the json_schema field, the -j flag in the CLI, Pydantic and Zod schemas, and hand-written GBNF grammars.

It also lists the schema features that are not supported, so you do not lose an afternoon to silent failures. Everything follows the official llama.cpp grammar and server docs as of December 2026.

TL;DR

  • Any valid JSON: send "response_format": {"type": "json_object"} to /v1/chat/completions.
  • Exact shape: {"type": "json_schema", "json_schema": {"name": "x", "schema": {...}}}. The OpenAI wrapper form is accepted.
  • CLI: llama-cli -m model.gguf -j '{...schema...}' -p "..."
  • Custom formats: write a GBNF grammar and pass --grammar-file or the grammar field.
  • Important: the schema is not shown to the model. Describe the fields in your prompt too.

How Constrained Output Works

A language model picks one token at a time from a list of candidates. llama.cpp can filter that list with a formal grammar. At every step, tokens that would break the grammar are removed, so the model can only write output that fits.

The grammar format is called GBNF (GGML BNF), an extension of Backus-Naur Form with regex-like features. When you pass a JSON schema, llama.cpp converts it to a GBNF grammar behind the scenes.

The result is valid syntax every time, even from small models. What it cannot do is make the model smart: a 1B model will still fill your fields with weak content. Constrained output fixes the shape, not the quality.

If you have not set up the server yet, start with how to install llama.cpp and the llama-server guide.

Every Way to Get JSON

Method Where Best for
response_format: json_object /v1/chat/completions Any valid JSON, quick start
response_format: json_schema /v1/chat/completions Apps using OpenAI SDKs
json_schema body field /completion and other completion endpoints Raw prompts without chat templates
grammar body field Completion endpoints Custom non-JSON formats
-j / --json-schema llama-cli, llama-completion, llama-server Terminal and scripts
--grammar / --grammar-file CLI and server Fixed grammar for every request

Any JSON With json_object

The simplest option forces valid JSON without a fixed structure. Start the server:

llama-server -hf ggml-org/gemma-3-4b-it-GGUF --port 8080

Then send a request:

curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "system", "content": "Reply only with JSON."},
      {"role": "user", "content": "Give me a name and a city for a fictional person."}
    ],
    "response_format": {"type": "json_object"}
  }'

The reply content is guaranteed to parse with JSON.parse or json.loads. Field names are up to the model, so use this for exploration, not production.

Exact Shape With a JSON Schema

For real apps, define the fields. llama.cpp accepts three forms in response_format:

  • {"type": "json_object", "schema": {...}}
  • {"type": "json_schema", "schema": {...}}
  • The OpenAI wrapper: {"type": "json_schema", "json_schema": {"name": "...", "strict": true, "schema": {...}}}
  1. Write the schema with types and required fields:
    {
      "type": "object",
      "properties": {
        "title":    {"type": "string", "minLength": 3, "maxLength": 80},
        "rating":   {"type": "integer", "minimum": 1, "maximum": 5},
        "tags":     {"type": "array", "items": {"type": "string"}, "maxItems": 5},
        "sentiment":{"type": "string", "enum": ["positive", "neutral", "negative"]}
      },
      "required": ["title", "rating", "tags", "sentiment"]
    }
  2. Describe the same fields in the prompt. The schema only filters tokens; the model never sees it. Say what each field means.
  3. Send the request:
    curl http://localhost:8080/v1/chat/completions \
      -H "Content-Type: application/json" \
      -d '{
        "messages": [{"role": "user", "content": "Review: The battery lasts two days but the camera is weak. Return title, rating 1-5, up to 5 tags and sentiment."}],
        "response_format": {
          "type": "json_schema",
          "json_schema": {"name": "review", "schema": { ...schema above... }}
        }
      }'
  4. Parse and validate. The shape is enforced, but validate in code anyway, since some schema keywords are skipped (see the limits section).

For raw prompts on /completion, pass the schema as "json_schema": {...} at the top level of the body instead. {} means any JSON.

Python With the OpenAI SDK and Pydantic

Because the server speaks the OpenAI format, the official Python SDK works. Pydantic generates the schema for you:

from openai import OpenAI
from pydantic import BaseModel

class Review(BaseModel):
    title: str
    rating: int
    tags: list[str]
    sentiment: str

client = OpenAI(base_url="http://localhost:8080/v1", api_key="none")

resp = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content":
        "Review: Fast shipping, cheap build. Give title, rating 1-5, tags, sentiment."}],
    response_format={
        "type": "json_schema",
        "json_schema": {"name": "review", "schema": Review.model_json_schema()},
    },
)
review = Review.model_validate_json(resp.choices[0].message.content)
print(review)

Pydantic sets additionalProperties only if you ask. llama.cpp defaults it to false, which is faster and reduces made-up keys. To allow extra keys, set extra = 'allow' on the model config.

In JavaScript, Zod plus zod-to-json-schema does the same job. Note that it always sets additionalProperties: false.

Comparing providers? Our structured outputs guide for Claude, OpenAI and Gemini shows the cloud versions, and Ollama structured outputs covers the Ollama API.

JSON From llama-cli

Pass a schema with -j for terminal use and shell scripts. This example from the docs asks for 10 to 100 actors:

llama-cli -hf bartowski/Phi-3-medium-128k-instruct-GGUF \
  -j '{
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "name": {"type": "string", "minLength": 1, "maxLength": 100},
        "age":  {"type": "integer", "minimum": 0, "maximum": 150}
      },
      "required": ["name", "age"],
      "additionalProperties": false
    },
    "minItems": 10, "maxItems": 100
  }' \
  -p 'Generate a {name, age}[] JSON array with famous actors of all ages.'

For one-shot scripts, llama-completion takes the same flag and exits after the answer. Passing -j or --grammar-file to llama-server applies it to every request, which suits a single-purpose extraction server.

Write a GBNF Grammar

Grammars handle formats JSON schema cannot, such as a fixed list of words, CSV lines or a custom DSL. Each rule has the form name ::= sequence, and root is the starting rule.

Syntax Meaning
"text" Literal characters
[a-z], [^\n] Character range, negated range
a | b Alternatives
( ... ) Grouping
*, +, ? Zero or more, one or more, optional
{m}, {m,n} Exact or bounded repetition
<think>, <[1000]> Match a whole tokenizer token by text or ID
# comment Comment

A yes or no classifier:

root ::= "yes" | "no"

A bullet list of up to five items:

root ::= ("- " item){1,5}
item ::= [^\n]+ "\n"

Save it as list.gbnf and run llama-cli -m model.gguf --grammar-file list.gbnf -p "Five uses for a GPU". On the server, send the grammar text in the grammar field of a /completion request. The llama.cpp repo ships ready grammars in grammars/, including json.gbnf and a chess example.

Performance tip: write x{0,5}, not x? x? x? x? x?. The docs warn that chained optional items can make sampling extremely slow.

Unsupported Schema Features

llama.cpp supports a subset of JSON Schema. Unsupported keywords are skipped silently, which is the main source of confusion.

Feature Status
type, properties, required, items, enum Supported
minLength, maxLength, minItems, maxItems Supported
minimum / maximum Integers only, not number
pattern Must start with ^ and end with $
properties mixed with anyOf/oneOf Not supported in the same type
prefixItems, nested $ref Broken
Remote $ref Not supported in C++
Formats uri, email Missing
patternProperties, uniqueItems, contains, not, if/then/else Not supported

The docs advise converting your schema ahead of time with the project’s command-line Python converter to see any warnings, then testing the grammar against sample strings with the GBNF validator. Validate parsed results in your own code as a final safety net.

Tips for Better Results

  • Put the field list in the prompt. This is the single biggest quality win, because the model never sees the schema.
  • Use enums for categories instead of free text.
  • Cap strings and arrays with maxLength and maxItems so the model cannot ramble until it hits the token limit.
  • Keep schemas flat. Deep nesting and refs are where support is weakest.
  • Thinking models: if the model has a reasoning phase, send "chat_template_kwargs": {"enable_thinking": false} or "reasoning_effort": "none" for short extraction tasks.
  • Need tool calls instead? Use llama.cpp function calling. For tools, schemas are injected into the prompt.

Troubleshooting

The output is cut off and will not parse

The token limit ended the reply mid-object. Raise max_tokens (or n_predict) and cap string lengths in the schema.

A constraint like minimum on a decimal is ignored

Numeric bounds only work on integer. Use an integer field, or validate in code.

Generation became very slow

Check for chained optional symbols in a grammar, or additionalProperties: true, which builds large grammars. Simplify the schema.

The fields are valid but full of nonsense

The model does not know what the fields mean. Describe them in the prompt, give one example, or use a larger model.

Error: grammar failed to parse

Rule names must be lowercase words with dashes. Token rules like <think> only work if the text is exactly one token in the model’s vocabulary.

FAQ

Does llama.cpp support structured output?

Yes. It supports JSON mode, JSON schemas and custom GBNF grammars in the server, CLI and completion tools.

Is llama.cpp JSON mode OpenAI compatible?

Yes. response_format with json_object or json_schema works on /v1/chat/completions, including the OpenAI wrapper form with name and strict.

What is GBNF?

GBNF is llama.cpp’s grammar format, based on Backus-Naur Form with regex-like repetition. It constrains which tokens the model can produce.

Does the model see my JSON schema?

No. The schema only constrains sampling. Describe the structure in your prompt. Tool calling is the exception, where schemas are added to the prompt.

Does constrained output slow down generation?

Simple schemas add little overhead. Very large or deeply optional grammars can slow sampling noticeably.

Can I use structured output with Open WebUI or other apps?

Only if the app sends response_format in its requests. Most chat UIs do not, so use the API or SDK directly.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a brick-walled loft holding a tablet with a JSON OUTPUT card, hook perfect JSON every time