Reliable JSON Output from LLMs: JSON Mode vs Structured Outputs

Blog / AI concepts

Reliable JSON Output from LLMs: JSON Mode vs Structured Outputs

To get an LLM to output JSON reliably, think in three layers. Prompt constraints only reduce the chance of errors. JSON mode guarantees the output is syntactically valid JSON, but not that the fields are right. Structured outputs with a JSON Schema constrain the fields and types to the schema you provide. Whichever layer you use, the calling code should still validate the result and retry on failure.

This article explains how the three approaches differ, when to pick each, and gives a validation-and-retry snippet you can adapt. Parameter names and supported features vary by provider and change over time, so check the official docs for specifics.

Why does JSON from an LLM so often fail to parse?

A model generates text one token at a time. It has no built-in notion that the output "must be valid JSON". Common failures include:

  • Explanatory text before or after the JSON, or the JSON wrapped in a Markdown code fence (three backticks plus json).
  • A missing comma, a trailing comma, or unescaped quotes inside a string.
  • Output cut off by max_tokens, leaving brackets unclosed.
  • Valid syntax but wrong content: a misspelled field name, a missing field, or a number written as a string.

The first three are syntax problems and the last is a content problem. JSON mode fixes most of the syntax problems; structured outputs also handle the content problem.

How do the three approaches differ?

ApproachWhat it guaranteesWhat it does not guaranteeBest for
Prompt constraintsNo hard guarantee; relies on the model following instructionsSyntax, fields, and types can all be wrongPrototyping, or when the model supports nothing else
JSON modeOutput is syntactically valid JSONField names, types, required fieldsSimple fields where you validate yourself
JSON Schema structured outputsOutput conforms to the given schemaWhether the values make business senseProduction, or many fields

How do you write a prompt that works?

Prompts still matter, because the other two approaches also rely on them to explain what the fields mean. A few guidelines:

  1. State explicitly: "Output a single JSON object and no other text."
  2. List the fields, with types and allowed value ranges.
  3. Include one complete example of the expected output.
  4. For values that may be absent, say whether to use null or omit the field.

What is JSON mode?

Using OpenAI's Chat Completions API as the example, JSON mode means adding response_format: {"type": "json_object"} to the request. According to the official docs, the output will then be valid JSON, but the docs also require you to mention JSON explicitly in the prompt, otherwise you may see unexpected behavior. It also doesn't constrain fields, so the structure you want still has to be described in the prompt.

If you're not yet sure how the messages array works, start with What is the Chat Completions API? How to write the messages array.

What are structured outputs?

Structured outputs mean passing type: "json_schema" in response_format, along with a name and a JSON Schema, and usually turning on strict mode. The output is then constrained to that schema, so fields, types, and required properties follow your definition. The supported schema keywords are limited. For example, strict mode generally requires every field to be listed as required and disallows extra properties on objects. Check the official docs for the exact limits.

Anthropic takes a different route. For a long time, Claude returned structured results through tool use: you define the structure you want as a tool's input_schema and have the model "call" it. Anthropic has since added a more direct structured output capability; whether it's available to you and how to enable it is covered in the official docs. For how tool calling works, see What is Function Calling? A beginner's guide to tool use.

How do you validate and retry in code?

Don't assume the first response is correct. The following approach is vendor-neutral; replace call_model with your own request function.

import json
from jsonschema import validate, ValidationError

SCHEMA = {
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "priority": {"type": "integer", "minimum": 1, "maximum": 5},
        "tags": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["title", "priority", "tags"],
    "additionalProperties": False,
}

def extract_json(text: str) -> str:
    # Strip a possible code-fence wrapper
    text = text.strip()
    if text.startswith("```"):
        text = text.split("\n", 1)[1].rsplit("```", 1)[0]
    return text

def get_structured(messages, max_retries=2):
    last_error = None
    for _ in range(max_retries + 1):
        raw = call_model(messages)          # returns the model's text
        try:
            data = json.loads(extract_json(raw))
            validate(data, SCHEMA)
            return data
        except (json.JSONDecodeError, ValidationError) as e:
            last_error = e
            # Send the error back to the model so it can correct itself
            messages = messages + [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": f"上面的输出不合法:{e}。请只输出修正后的 JSON。"},
            ]
    raise RuntimeError(f"多次重试仍失败:{last_error}")

A few practical notes:

  • Cap the number of retries. Every retry costs more tokens; see How is LLM API cost calculated? A formula you can reuse for the math.
  • Leave enough room in max_tokens. When output is truncated, check the finish reason in the response (for example finish_reason equal to length). Retrying the same request is pointless in that case; raise the limit or simplify the structure.
  • Lower temperature. For extraction tasks this is usually more stable.
  • If the model refuses, the response may contain a refusal message instead of JSON. Handle that case separately.

Which one should you choose?

Work through this order:

  1. If your model and endpoint support JSON Schema structured outputs, use them first, and add a local validation layer on top.
  2. If only JSON mode is supported, use it, put the field descriptions and an example in the prompt, and validate locally against the schema.
  3. If neither is supported, rely on the prompt plus extraction and retries, and accept a higher failure rate.
  4. In every case, business meaning (is the date plausible, is the amount positive) can only be checked by your own code.

If the task is really about letting the model decide which function to call, tool calling is a better fit than hand-assembling JSON. MCP is also designed around this kind of structured interaction; see What is MCP? A beginner's introduction to the Model Context Protocol.

How do you get started trying this?

To experiment with these parameters you need an API you can call. For the official routes, see How to get an OpenAI API key and How to get a Claude API key. Once you have a key, follow How to use an LLM API: from getting a key to your first reply to send your first request.

If you're in mainland China and don't have an overseas credit card, you could also consider AGI Plan. AGI Plan is a commercial partner of cdnping, and the description below comes from its own website. It is an aggregation gateway for multiple LLM providers, billed as a monthly subscription, paid in RMB, with no overseas credit card needed. It is compatible with both the OpenAI and Anthropic API formats, so tools like Claude Code and Codex only need a single endpoint URL changed. The site states plainly that it is not an officially authorized channel and that some models are available only outside China. Whether a particular parameter or structured output mode is supported is something to confirm on the models page and in the official docs. For setup steps, see the AGI Plan getting-started guide.

If calls aren't going through, first use cdnping's online speed test to check your connection to each provider's API, or check the API status page to confirm the official endpoint is up.

Summary and next steps

Use the strongest constraint available (a schema), then validate in code, and keep retries as the last line of defense. Two things to do now: write your output structure as a JSON Schema, then wire the get_structured function above to your request function and run a dozen real inputs through it to see which kind of failure dominates.

Related articles

Keep reading