Lesson 8 of 15 · Core Techniques
Asking for Structured Output
Get output a program can use: ask for JSON with a clear schema, allowed values and nulls, use structured output modes, and parse and validate replies in Python.
- 7 min read
- Beginner
- Reviewed
- When you need structured output instead of free text
- How to describe the exact shape you want, including JSON
- How to handle missing information without the model guessing
- How to read and check a model's structured reply in code
Text for people, structure for programs
A paragraph is perfect for a person to read. But if the output goes into a spreadsheet, a database or another program, you need a fixed shape every time: the same fields, the same names, the same kinds of values.
Prompt
Read this support email and tell me who sent it, what it is about and whether it is urgent. <email>Hi, this is Asha Patel. I've been charged twice for March and my rent is due tomorrow. Please help!</email>
Example response
This email is from Asha Patel. She is writing about a billing problem: she was charged twice for March. It seems fairly urgent, as she mentions her rent is due tomorrow.
Fine for a person. A program would have to guess where the name, topic and urgency are in the sentence.
How to ask for structure
- Name the format. "Reply with JSON only", "a CSV with these columns", "a Markdown table with columns Task, Owner, Date".
- Describe every field: its name, its type (text, number, true/false, list) and, for categories, the allowed values.
- Show an example of one complete output.
- Say what to do when information is missing. "If a field is not in the text, use null." Otherwise the model may invent a plausible value.
- Say "no other text" if a program will read it, so there is no friendly introduction to strip off.
Reading the reply in code
Once the reply is JSON, Python's json module turns it into a dictionary in one line.
import json
# The model's reply. We asked for JSON only, and it obeyed.
reply = '{"name": "Asha Patel", "topic": "billing", "urgent": true, "order_id": null}'
data = json.loads(reply) # turn the JSON text into a Python dictionary
print("Name:", data["name"])
print("Topic:", data["topic"])
print("Urgent?", data["urgent"])
print("Order ID:", data["order_id"])JSON's true became Python's True, and null became None. Because the prompt said "use null if missing", the program can tell "not given" apart from a made-up value.
Always check the reply
Even with clear instructions, replies sometimes have extra text, missing fields or a value outside the allowed list. Good code checks before trusting.
import json
# A messier reply: the model added chatty text around the JSON
reply = 'Sure! Here is the data:\n{"name": "Ben Ode", "topic": "refund", "urgent": "yes"}\nAnything else?'
# 1. Cut out the part from the first { to the last }
start = reply.find("{")
end = reply.rfind("}") + 1
data = json.loads(reply[start:end])
# 2. Check it against the rules we gave in the prompt
allowed_topics = ["billing", "bug", "feature request"]
problems = []
for key in ["name", "topic", "urgent", "order_id"]:
if key not in data:
problems.append("missing field: " + key)
if data.get("topic") not in allowed_topics:
problems.append("topic must be one of: " + ", ".join(allowed_topics))
if not isinstance(data.get("urgent"), bool):
problems.append("urgent must be true or false")
if problems:
for problem in problems:
print("Problem:", problem)
else:
print("Valid:", data)All three problems are caught: a missing field, a topic outside the list and "yes" instead of true. A real app would then retry with the problems listed in a follow-up message, or flag the item for a person.
Common mistakes
A model extracted the items from a receipt as JSON. Read it in Python and add up the bill.
import json
reply = '{"items": [{"name": "tea", "price": 2.5}, {"name": "cake", "price": 3.0}]}'
# Parse the reply, print each item like "tea: 2.50",
# then print the total like "Total: 5.50"
Your schema has a field for the customer's order number, but many emails do not mention one. What should the prompt say?
Summary
- Use structured output (JSON, CSV, fixed tables) when a program or spreadsheet will read the result.
- Name the format, describe each field and its allowed values, show an example and say "no other text".
- Tell the model to use null or "not set" for missing information, so it does not guess.
- Use an API's structured output mode when available.
- Parse and validate replies in code, and retry or flag the ones that fail.
Next: system prompts, the standing instructions behind every chat.
Finished reading? Tick it off to track your progress.