JSON Schema Output
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 13 of 22.
Code needs data it can read, not prose. Asking for JSON in the prompt is not enough: models often wrap it in a Markdown fence, such as ```json on the line before, and json.loads refuses that text.
Structured output fixes the format. Pass a JSON schema in output_config and the reply's text block holds JSON that matches it, so json.loads always works:
schema = {
"type": "object",
"properties": {"city": {"type": "string"}, "nights": {"type": "integer"}},
"required": ["city", "nights"],
"additionalProperties": False,
}
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=200,
messages=[{"role": "user", "content": "Book 4 nights in Lisbon for me."}],
output_config={"format": {"type": "json_schema", "schema": schema}},
)
trip = json.loads(response.content[0].text)
print(trip["city"], trip["nights"])This prints Lisbon 4. properties names each field and its type, required lists the fields that must be there, and "additionalProperties": False forbids extra fields, as Anthropic's own examples do. The model still decides the values, so a field can be wrong even when the JSON is valid.
Challenge
MediumTurn a customer's order message into data. The starter reads the message and defines SCHEMA with a name, an email and a quantity.
- Send the message as the only user turn with
model="claude-opus-5-5",max_tokens=300and anoutput_configwhose format is the JSON schemaSCHEMA. - Parse the reply text with
json.loads. - Print
Name:,Email:andQuantity:, each followed by its field, one per line.
For example, for the input Hi, I am Rosa Diaz (rosa@example.com) and I want 3 lamps. the program prints:
Name: Rosa Diaz
Email: rosa@example.com
Quantity: 3Try it yourself
import coddy_ai as anthropic # in production: import anthropic
import json
client = anthropic.Anthropic()
SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"quantity": {"type": "integer"},
},
"required": ["name", "email", "quantity"],
"additionalProperties": False,
}
order = input()
# Ask for the order's details as JSON that follows SCHEMA, parse the reply,
# then print the name, the email and the quantity
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
3Tokens and Structure
Counting Tokens and CostHandling API ErrorsJSON Schema OutputClassifying With EnumsRecap: Review SorterPractice on your own: Online Python compiler