TExcelTAD
Home › Generative AI & LLMs › Structured Output (JSON)

Structured Output (JSON)

Text is great for people, but programs need structure. If your code must read an LLM's answer — to store fields in a database, call a function, or show a form — ask for JSON and validate it before you trust it. This lesson shows how to request, extract, validate and repair structured output.

Asking for JSON

Describe the exact shape you want, ideally with an example or a schema:

python · try it yourself
import json

schema_example = {
    "name": "string",
    "email": "string or null",
    "topic": "one of: billing, delivery, product, other",
    "urgent": "boolean",
}

prompt = (
    "Extract the fields below from the customer message.\n"
    "Reply with a single JSON object and nothing else, using exactly these keys:\n"
    f"{json.dumps(schema_example, indent=2)}\n\n"
    "<message>Hi, this is Ana Silva (ana@example.com). "
    "My parcel was due Monday and still hasn't arrived - I need it for a wedding on Saturday!</message>"
)
print(prompt)
Extract the fields below from the customer message.
Reply with a single JSON object and nothing else, using exactly these keys:
{
  "name": "string",
  "email": "string or null",
  "topic": "one of: billing, delivery, product, other",
  "urgent": "boolean"
}

<message>Hi, this is Ana Silva (ana@example.com). My parcel was due Monday and still hasn't arrived - I need it for a wedding on Saturday!</message>

A typical reply is a JSON object such as {"name": "Ana Silva", "email": "ana@example.com", "topic": "delivery", "urgent": true} — but "typical" is not "guaranteed". Replies can arrive wrapped in a markdown code fence, with a polite sentence in front, with a missing key, or with "urgent": "yes" instead of a boolean.

Step 1: extract the JSON

python · try it yourself
import json
import re

def extract_json(reply):
    # strip a ```json ... ``` fence if present
    fenced = re.search(r"```(?:json)?\s*(.*?)```", reply, re.DOTALL)
    if fenced:
        reply = fenced.group(1)
    # otherwise take the outermost {...}
    start, end = reply.find("{"), reply.rfind("}")
    if start == -1 or end == -1:
        raise ValueError("no JSON object found")
    return json.loads(reply[start:end + 1])

replies = [
    '{"name": "Ana", "urgent": true}',
    'Sure! Here is the data:\n```json\n{"name": "Ana", "urgent": true}\n```',
    'Here you go: {"name": "Ana", "urgent": true} Let me know if you need more.',
    "Sorry, I can't find a name.",
]
for r in replies:
    try:
        print("ok:   ", extract_json(r))
    except ValueError as e:
        print("error:", e)
ok:    {'name': 'Ana', 'urgent': True}
ok:    {'name': 'Ana', 'urgent': True}
ok:    {'name': 'Ana', 'urgent': True}
error: no JSON object found

(json.JSONDecodeError is a subclass of ValueError, so the except also catches broken JSON.)

Step 2: validate the fields

Parsing proves the text is JSON — not that it has the right keys, types and values. Check those explicitly:

python · try it yourself
ALLOWED_TOPICS = {"billing", "delivery", "product", "other"}

def validate(data):
    errors = []
    expected = {"name": str, "email": (str, type(None)), "topic": str, "urgent": bool}
    for key, typ in expected.items():
        if key not in data:
            errors.append(f"missing key '{key}'")
        elif not isinstance(data[key], typ):
            errors.append(f"'{key}' has wrong type {type(data[key]).__name__}")
    extra = sorted(set(data) - set(expected))
    if extra:
        errors.append(f"unexpected keys {extra}")
    if data.get("topic") not in ALLOWED_TOPICS:
        errors.append(f"topic {data.get('topic')!r} not allowed")
    return errors

samples = [
    {"name": "Ana Silva", "email": "ana@example.com", "topic": "delivery", "urgent": True},
    {"name": "Ana Silva", "email": None, "topic": "shipping", "urgent": "yes"},
    {"name": "Ana Silva", "topic": "delivery", "urgent": False, "mood": "angry"},
]
for s in samples:
    print(validate(s) or "valid")
valid
["'urgent' has wrong type str", "topic 'shipping' not allowed"]
["missing key 'email'", "unexpected keys ['mood']"]

In real projects you would typically use a schema library such as Pydantic or jsonschema, which do the same checks with less code.

Step 3: retry with feedback

If validation fails, a common pattern is to send the errors back and ask the model to fix its output — with a maximum number of attempts. Below, a fake model (a function returning canned replies) stands in for the API, so the loop is fully deterministic:

python · try it yourself
import json

canned = iter([
    '{"name": "Ana Silva", "topic": "shipping", "urgent": "yes"}',
    '{"name": "Ana Silva", "email": null, "topic": "delivery", "urgent": true}',
])

def fake_model(prompt):
    return next(canned)

def validate(d):
    errs = [f"missing '{k}'" for k in ("name", "email", "topic", "urgent") if k not in d]
    if d.get("topic") not in {"billing", "delivery", "product", "other"}:
        errs.append("topic must be billing, delivery, product or other")
    if not isinstance(d.get("urgent"), bool):
        errs.append("urgent must be true or false")
    return errs

prompt = "Extract name, email, topic, urgent as JSON from: ..."
for attempt in range(1, 4):
    data = json.loads(fake_model(prompt))
    errors = validate(data)
    print(f"attempt {attempt}: {errors or 'valid'}")
    if not errors:
        break
    prompt += "\nYour previous answer had these problems: " + "; ".join(errors) + ". Please fix them."
print("result:", data)
attempt 1: ["missing 'email'", 'topic must be billing, delivery, product or other', 'urgent must be true or false']
attempt 2: valid
result: {'name': 'Ana Silva', 'email': None, 'topic': 'delivery', 'urgent': True}

Let the API enforce the structure

Many providers now offer features that constrain output to a JSON schema (often called structured outputs or JSON mode), and tool use (next section) naturally returns arguments as JSON matching a schema you define. These greatly reduce format errors. Even then, keep validating the values: a schema can guarantee urgent is a boolean, not that it is the correct boolean.

Tip: Keep schemas small and flat when you can, use enums for categories, and allow null for fields that may be missing — that gives the model an honest way to say "not present" instead of inventing a value.

Test yourself

The reply parses as valid JSON. What can you still not assume?

  1. That it is text
  2. That it has the right keys, types and allowed values
  3. That it contains braces
  4. That json.loads worked

Why is allowing null for optional fields helpful?

  1. It makes JSON shorter
  2. It gives the model an honest way to say a value is absent instead of inventing one
  3. null is required by JSON
  4. It speeds up parsing

What should a retry loop for invalid output always have?

  1. Infinite retries
  2. A maximum number of attempts and a fallback
  3. Temperature set to 2
  4. No error messages