Skip to content

Parse structured output safely

Get schema-valid output with structured outputs or strict tool use, check the stop reason before parsing, and validate in code the rules a schema can't express.

Scenario

An expense-report service asks Claude to "return only JSON" for each scanned receipt. Most nights it works. Then three things happen in one week: a parse error stops the queue, a 90-line hotel bill comes back cut off mid-array, and a perfectly valid JSON object books a total that doesn't match its own line items.

Three different failures, and only the first is about JSON syntax.

Explanation

Get the shape guaranteed, not requested. Asking for "only JSON" reduces failures but can't remove them. Structured outputs use constrained decoding, so the output follows your schema:

  • JSON outputs (output_config.format with type: "json_schema") control what Claude says: the response's text is JSON that matches your schema. The SDKs' parse() helpers take a Pydantic or Zod type and return the result in parsed_output.
  • Strict tool use (strict: true on a tool definition) controls how Claude calls your functions: tool inputs match the tool's input_schema, so you get 2, not "2" or "two".

Use JSON outputs for extraction and reports, strict tool use for agents that call functions, or both in one request.

Check the stop reason before you parse. The guarantee holds for a complete response:

stop_reason What it means for your JSON
max_tokens Cut off: the JSON may be incomplete. Retry with a higher max_tokens
refusal The refusal takes precedence, so the output may not match the schema
end_turn Complete: parse it

Validate what the schema can't express. The schema subset leaves out numeric and length constraints such as minimum, maximum and maxLength (SDK helpers move them into the field description and can check them in your code), and it says nothing about business rules: totals that add up, dates in range, IDs that exist. Enum values can also differ in capitalization, so compare them case-insensitively.

Stay sceptical of confident output. A valid object can hold an invented value with the same confidence as a true one. Check rules in code, retry with the specific error, and send what still fails to a person.

Worked example

Before:

resp = client.messages.create(**request)
data = json.loads(resp.content[0].text)
book_expense(data)

After (the request carries output_config with the schema):

resp = client.messages.create(**request)
if resp.stop_reason == "max_tokens":
    return retry(request, max_tokens=8192)
if resp.stop_reason != "end_turn":
    return send_to_review(request)
text = next(b.text for b in resp.content
            if b.type == "text")
exp = json.loads(text)
lines = sum(item["amount"] for item in exp["items"])
if abs(lines - exp["total"]) > 0.01:
    return send_to_review(request)
book_expense(exp)

The parse error can't happen with the schema enforced, the cut-off bill is retried instead of half-parsed, and the mismatched total goes to a person instead of the ledger.