Structured Outputs
Reliable data from messy text.
Software likes tidy data, and people write messy text. Generative A I is superb at turning one into the other. In this lesson, you will learn how to get reliable, structured results, that your programs can trust.

- Messy text in, tidy data out
- Reliable formats for programs
- Schemas and validation
Extracting data as JSON
Here we ask the model to read a customer message, and extract the details. We tell it to reply with J S O N only, with exact fields. Then we parse the answer with json loads, and use it like any Python dictionary. With a low temperature, the results are consistent. This simple pattern powers many real products.
import json
from openai import OpenAI
client = OpenAI()
msg = "Hi, I'm Sara. My order #4821 arrived broken. I want a refund."
prompt = f"""Extract JSON with keys name, order_id, problem, wants.
Reply with JSON only.\n\nMessage: {msg}"""
reply = client.chat.completions.create(
model="gpt-4o-mini", temperature=0,
messages=[{"role": "user", "content": prompt}])
data = json.loads(reply.choices[0].message.content)
print(data["order_id"], data["wants"])Why validation matters
But models can still slip. A field may be missing, a number may arrive as text, or the model may add a friendly sentence before the J S O N. So never trust blindly. Define the shape you expect, with a schema, and validate every answer. If it fails the check, retry, or ask the model to fix its own output. Most providers also offer a structured output mode, that guarantees valid J S O N.
Without validation
- Trust whatever comes back
- Crashes on a missing field
- Silent wrong data
- Hard to debug
With validation
- Define the expected schema
- Check every answer
- Retry or repair on failure
- Safe for real systems
Where structure helps
Structured output unlocks many uses. Sorting support tickets into categories. Extracting names, dates, and amounts from invoices. Turning meeting notes into action items. Labelling thousands of reviews, as positive, or negative. Filling a database, from free text. Anywhere you have messy words, and need clean fields, this pattern applies.
Summary
Good. Ask for J S O N with exact fields, set a low temperature, and always validate. Retry, or repair, when something is off. This turns messy text into data that software can use. Next, the business side of A I, cost, speed, and streaming.
Key takeaways- Ask for JSON, exact fields
- Validate every answer
- Retry or repair on failure