News / Learn / Prompt engineering
How do you get reliable JSON out of a model?
You'll be able to get a model to return JSON your code can parse, and handle the cases where it doesn't.
In plain English
A language model writes text one token at a time. It does not know your code expects a specific shape. Getting reliable JSON means you define the shape, constrain the output where the provider allows it, and check the result before you use it.
Why it matters
Your product probably passes model output into other code: a database write, a UI component, a tool call. One malformed reply can crash a request or corrupt data. Treating model output as untrusted input, the same way you treat user input, keeps your app stable.
How it works
Start by describing the exact shape you want. Name every field, its type, and what it means. Put that description in the prompt and give one short example of a valid reply. This helps, but it is not a guarantee.
Next, use the strongest format control your provider offers. Many APIs support structured output, where you pass a JSON schema and the decoder is limited to valid output. Some offer a simpler JSON mode that guarantees valid JSON syntax but not your fields. Use the stricter option when it exists, since it removes whole classes of errors.
Then validate. Parse the text with a JSON parser, and check the result against a schema with a validation library. Reject anything that fails. Do not assume a parse succeeded just because no exception was thrown, because the object may still be missing fields or hold the wrong types.
Finally, plan for failure. Retry with the validation error included in the prompt, usually once or twice. If it still fails, fall back to a safe default or show an error. Log failures so you can see which inputs cause trouble and improve the prompt over time.
A concrete example
A minimal pattern: define a schema, ask for JSON, parse, validate, and retry once with the error.
import json
from pydantic import BaseModel, ValidationError
class Ticket(BaseModel):
title: str
priority: int # 1 to 3
tags: list[str]
def get_ticket(call_model, text: str, retries: int = 1) -> Ticket:
prompt = (
"Extract a ticket from the text below. Reply with only JSON that has "
"keys: title (string), priority (integer 1-3), tags (array of strings).\n\n"
+ text
)
error = None
for _ in range(retries + 1):
p = prompt if error is None else prompt + f"\n\nYour last reply was invalid: {error}. Fix it."
raw = call_model(p)
try:
return Ticket.model_validate(json.loads(raw))
except (json.JSONDecodeError, ValidationError) as e:
error = str(e)
raise ValueError(f"Model did not return valid JSON: {error}")A short sketch to show the idea. Check the official docs of the tool you use.
What goes wrong
- Trusting the prompt alone Instructions reduce errors but do not stop them. Use structured output or JSON mode where available, and always validate in your code.
- Parsing without validating types Valid JSON can still have missing keys, wrong types, or out-of-range values. Check every field against a schema before use.
- Extracting JSON with string tricks Stripping markdown fences or slicing between braces breaks on nested or quoted text. Use a real parser and a constrained output mode.
- Retrying forever Cap retries and include the validation error in the retry prompt. Then fall back or fail clearly, and log the input for review.
Going deeper
Learn JSON Schema, since most structured output features and validators use it. Then study how your provider's constrained decoding works and what its limits are, such as supported schema features and size limits.
FAQ
Is JSON mode the same as structured output?
No. JSON mode usually guarantees syntactically valid JSON. Structured output with a schema also constrains the fields and types. Prefer the schema version when your provider offers it.
Why does the model sometimes add text before the JSON?
The model is trained to be conversational, so it may add a preamble or a code fence. Constrained output modes prevent this. Otherwise, strip known wrappers before parsing, then validate.
Should I lower temperature for JSON?
Lower temperature often makes output more consistent, which can help. It does not guarantee valid structure, so keep validation in place either way.
What if a required value is not in the input?
Define how the model should signal that, such as null or an empty list, and allow it in your schema. Otherwise the model will invent a value to fill the field.
Written with AI by CapyLaunch. Spotted a mistake? Email hello@capylaunch.com.