← Building with AI

Asking for JSON

Get answers your code can read, not just sentences.

Start this lesson

A sentence is great for people but awkward for programs. If you want to use the answer in code (save it, sort it, show it in a table), ask the model to reply in JSON with exact key names. JSON looks like a Python dict, and json.loads turns the reply text into a real dict you can use.

# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
import anthropic, json
client = anthropic.Anthropic()

text = "Mei is 29 and lives in Taipei."
prompt = (
    "Extract the person's name, age and city from the text.\n"
    'Reply with only JSON like {"name": "...", "age": 0, "city": "..."}.\n'
    f"Text: {text}"
)
reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=200,
                               messages=[{"role": "user", "content": prompt}])
data = json.loads(reply.content[0].text)
print(data["city"])   # Taipei

json.loads reads JSON text and returns a Python dict. Showing the exact shape you want makes the reply much more reliable.

In this unit the pretend model is a simple function ask_model(prompt) that takes a prompt string and returns text. Many real programs wrap the SDK call in a helper like that.

Some APIs have a special 'structured outputs' or tool feature that guarantees the format. Even then it is good practice to parse and check the result, which is what the next lessons cover.