AI & prompting

How to Get JSON From an LLM Reliably (Schemas, Parsing, Retries)

To get JSON from an LLM reliably, pass a JSON Schema through the API's structured output feature (output_config.format in Anthropic's Messages API, text.format with "type": "json_schema" in OpenAI's Responses API, or format in Ollama), which constrains the model so its reply matches the schema. Then still parse and validate the reply in code, because a refusal or a reply cut off at the token limit can break the structure even with a schema.

The four levels of reliability

There are four ways to ask a model for JSON, and they differ in what they actually guarantee:

MethodValid JSON?Matches your fields?When to use it
Ask in the prompt onlyUsually, not alwaysUsually, not alwaysQuick experiments, models with no structured output support
JSON modeYes (unless cut off)No guaranteeOlder models that lack schema support
Structured outputs (schema-constrained)Yes (unless cut off or refused)YesAnything that feeds code: extraction, classification, pipelines
Strict tool useYes, for the tool argumentsYesWhen the JSON is really a function call your code will execute

OpenAI's documentation states the difference plainly: JSON mode "will not guarantee the output matches any specific schema, only that it is valid and parses without errors". Structured outputs add schema adherence on top.

Structured outputs in the Anthropic API

Put the schema in output_config.format. This is the example from Anthropic's structured outputs docs:

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": "Extract the key information from this email: John Smith ([email protected]) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."
      }
    ],
    "output_config": {
      "format": {
        "type": "json_schema",
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "plan_interest": {"type": "string"},
            "demo_requested": {"type": "boolean"}
          },
          "required": ["name", "email", "plan_interest", "demo_requested"],
          "additionalProperties": false
        }
      }
    }
  }'

The JSON arrives as the text of the response's content block. Details from the docs worth knowing, as of October 2026:

  • No beta header is needed. The older output_format parameter is deprecated and returns a 400 error unless you send the structured-outputs-2025-11-13 beta header.
  • Objects must set "additionalProperties": false.
  • Not supported: recursive schemas, minimum/maximum/multipleOf, minLength/maxLength, and array minItems other than 0 or 1. Using them returns a 400 error.
  • Required properties come out first, then optional ones, regardless of the order in your schema.
  • The capitalisation of enum values is not guaranteed, so compare them case-insensitively.
  • Message prefilling (starting the assistant turn with {) is incompatible with JSON outputs.

Structured outputs in the OpenAI API

In the Responses API, the schema goes in text.format with a name and "strict": true. Trimmed from the example in OpenAI's guide:

"text": {
  "format": {
    "type": "json_schema",
    "name": "math_reasoning",
    "schema": {
      "type": "object",
      "properties": {
        "steps": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "explanation": { "type": "string" },
              "output": { "type": "string" }
            },
            "required": ["explanation", "output"],
            "additionalProperties": false
          }
        },
        "final_answer": { "type": "string" }
      },
      "required": ["steps", "final_answer"],
      "additionalProperties": false
    },
    "strict": true
  }
}

OpenAI's rules differ from Anthropic's in one important way: "all fields or function parameters must be specified as required". To make a value optional, give it a union type with null, such as "type": ["string", "null"]. A schema can have up to 5,000 object properties and 10 levels of nesting. In the older Chat Completions API, the same feature uses response_format with "type": "json_schema".

If you fall back to JSON mode ("type": "json_object"), the API "will throw an error if the string "JSON" does not appear somewhere in the context", so mention JSON in your instructions.

Structured outputs with a local model (Ollama)

Ollama accepts either "format": "json" for plain JSON mode or a full JSON Schema object in format. An example request following the pattern in Ollama's docs:

curl http://localhost:11434/api/chat -d '{
  "model": "gpt-oss",
  "messages": [{"role": "user", "content": "Describe Canada. Reply as JSON with name and capital."}],
  "stream": false,
  "format": {
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "capital": {"type": "string"}
    },
    "required": ["name", "capital"]
  }
}'

Replace the model name with one you have pulled. Ollama's docs give two tips: also include the schema in the prompt as text "to ground the model's response", and lower the temperature (for example to 0) for more repeatable output. Its docs also note that the cloud version did not support structured outputs at the time of writing. For setting up a local model in the first place, see how to run an LLM locally with Ollama.

When you can only prompt: getting JSON out of free text

Some models and providers have no schema support. Then the prompt has to do the work, and your code has to be forgiving about what comes back. In the prompt:

  • Show the exact shape, with every key, as a filled-in example.
  • Say "Reply with only the JSON object, no Markdown and no explanation."
  • Tell the model what to put when a value is unknown (null), so it doesn't invent one. Hallucinated values pass every JSON check.

Then expect replies like this anyway:

Sure! Here is the data:
```json
{"name": "Ada", "age": 36}
```

Calling json.loads() on that fails at the very first character. This is real output from Python 3.12:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Instead of stripping fences with string replacement, find the first { and let the decoder read exactly one JSON value from there. The Python docs describe raw_decode as a way to decode a JSON document "from a string that may have extraneous data at the end":

import json

def extract_json(reply: str) -> dict:
    start = reply.index("{")          # ValueError if there is no object at all
    obj, _end = json.JSONDecoder().raw_decode(reply[start:])
    return obj

print(extract_json('Sure! Here is the data:\n```json\n{"name": "Ada", "age": 36}\n```'))
{'name': 'Ada', 'age': 36}

The errors you'll see, and what each means

These are the exact messages from Python 3.12's json module for the usual LLM mistakes (newer Python versions word some of them differently):

Model outputErrorCause
Text or a code fence before the JSONExpecting value: line 1 column 1 (char 0)Preamble; use the extraction above
{'name': 'Ada'}Expecting property name enclosed in double quotes: line 1 column 2 (char 1)Python-style single quotes are not JSON
{"a": 1,}Expecting property name enclosed in double quotes: line 1 column 9 (char 8)Trailing comma
{"name": "Ada", "age": 36Expecting ',' delimiter: line 1 column 26 (char 25)Reply cut off before the closing brace

Don't paper over these with eval() or a regex that "repairs" JSON. eval executes whatever the model wrote, and the model's output can be influenced by any text in its input (see prompt injection).

Always check why the reply ended

A schema constrains what the model generates, but two situations still produce output that doesn't match it:

  • The token limit was hit. In Anthropic's API the response has stop_reason: "max_tokens" and "the output might be incomplete and not match your schema". In OpenAI's Responses API the response has status: "incomplete" with incomplete_details.reason set to "max_output_tokens". Retry with a higher limit, or ask for less output.
  • The model refused. Anthropic returns stop_reason: "refusal" with HTTP 200, and the refusal text "takes precedence over schema constraints". OpenAI's response includes a refusal field, which may not follow your schema. Check for both before parsing.

Output length is measured in tokens, not characters, so a long array of records can hit the limit sooner than you expect. The larely token counter gives a quick estimate of how many tokens a sample reply takes.

Validate after parsing, then retry once

Parsing proves the reply is JSON. It doesn't prove the values make sense. After json.loads, check what your code depends on: required keys present, types right, numbers in range (Anthropic's structured outputs can't enforce minimum or maximum, so range checks are yours), enum values from the allowed set. A validation library such as jsonschema or Pydantic does this against the same schema you sent.

When validation fails, one retry that includes the error message ("Your previous reply failed validation: age must be an integer") fixes most problems. If the second attempt also fails, log the raw reply and fail loudly rather than looping. Repeated failures usually mean the schema or the prompt is ambiguous, and the fix belongs there.

Frequently asked questions

What is the difference between JSON mode and structured outputs?
JSON mode only guarantees that the reply parses as JSON; it can still have the wrong fields or types. Structured outputs constrain generation to a JSON Schema you supply, so the reply also matches your field names, types and required keys. OpenAI's docs recommend structured outputs over JSON mode when the model supports it.
Why does the model wrap its JSON in ```json code fences?
Chat models are trained to format code for humans, and a code fence is how Markdown shows code. Ask for raw JSON with no Markdown, or better, use a structured output feature, which makes fences impossible. If you are stuck with free text, find the first { and parse from there instead of stripping fences with string replacement.
Can I make fields optional with structured outputs?
OpenAI requires every field to be listed in required and suggests a union with null, such as "type": ["string", "null"], for values that may be missing. Anthropic allows optional properties, but its docs say required properties are emitted first and that optional and union-type parameters count toward schema complexity limits.
Does temperature 0 guarantee valid JSON?
No. A lower temperature makes the output more repeatable, and Ollama's docs suggest it for structured output, but it does not stop the model from producing malformed or incomplete JSON. Only constrained decoding against a schema guarantees the structure, and even then a reply cut off by the token limit is incomplete.

Sources