Claude API

How do you force Claude to return valid JSON in API responses?

QUICK ANSWER

To force JSON output, declare your required JSON schema in a tool definition and set the tool_choice block to force a call to that tool, forcing Claude to structure the response as valid JSON arguments.

Forced JSON Schema Pattern

{
  "model": "claude-3-5-sonnet-20241022",
  "max_tokens": 1024,
  "tools": [{
    "name": "respond_json",
    "description": "Formats final response in standard structure.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "status": { "type": "string" },
        "data": { "type": "string" }
      },
      "required": ["status", "data"]
    }
  }],
  "tool_choice": { "type": "tool", "name": "respond_json" },
  "messages": [{"role": "user", "content": "Extract data from: Invoice 123 paid successfully."}]
}
Verified against: Anthropic API tool_choice spec