Interview Q&A / AI & Generative AI

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How would you get reliably structured JSON output from an LLM?

SHORT ANSWER

Describe the exact schema in the prompt with an example, use the provider's structured output or JSON mode if available, set a low temperature, then parse and validate against a schema in code, retrying or repairing when it fails.

Explain it simply

If your code expects a form with fixed boxes, a free-writing answer will break it. You need layers of protection, because none of them is perfect alone.

First, tell the model the exact fields, types and allowed values, and show one example. Second, if the API offers a structured output or schema-constrained mode, turn it on, since it limits generation to valid shapes. Third, use a low temperature. Fourth, never trust the result: parse it, validate it against a schema, and check values such as dates or enums.

When validation fails, retry once with the error message included, or fall back to a repair step. Log failures, because their rate is a useful quality metric.

Example

python
import json
raw = call_llm(prompt)           # asks for {"city": str, "pax": int}
try:
    data = json.loads(raw)
    assert isinstance(data["pax"], int)
except (ValueError, KeyError, AssertionError):
    raw = call_llm(prompt + "\nYour last reply was invalid. Return only valid JSON.")

What to say in the interview

"I specify the schema and an example, use constrained or JSON mode where available, keep temperature low, and always validate in code with a bounded retry. I track the invalid-output rate as a metric."

Common mistakes

  • Trusting that "return only JSON" in the prompt will always be obeyed.

#prompting#structured-output#json

Related questions

Practise more AI & Generative AI questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open AI & Generative AI quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.