← Blog

Claude API JSON Mode: Getting Structured Responses

2026-11-16 · 5 min read · SubToAPI Team

If you're searching for "Claude API JSON mode," the short answer is: Claude doesn't have a dedicated JSON mode like some other LLM APIs do. There's no response_format: { type: "json_object" } flag you can flip. But you can still get Claude to return clean, valid, parseable JSON on every single call — reliably enough to use in production pipelines.

This article covers the three practical approaches that work today: strict prompting with a system message, response prefilling, and tool-use schemas (the most reliable option). It also covers common failure modes and how to validate output before it hits your database.

Why Claude has no native JSON mode

Claude's API is built around natural-language instructions and tool definitions rather than output-format flags. Instead of a mode switch, Anthropic gives you two mechanisms that, combined, are more flexible than a simple JSON toggle:

  1. System prompts that describe the exact output contract you want.
  2. Tool use, where you define a JSON Schema and Claude returns arguments that validate against it.

If you only need "probably valid JSON most of the time," prompting is enough. If you need guaranteed schema-conformant output for a pipeline that feeds a database or downstream API, tool use is the right tool.

Method 1: System prompt + explicit instructions

The simplest approach is to tell Claude exactly what you want, including the schema, in the system prompt:

You must respond with valid JSON only. Do not include markdown code
fences, explanations, or any text outside the JSON object.

Schema:
{
  "name": string,
  "category": string,
  "price_usd": number,
  "in_stock": boolean
}

This works most of the time, but has two weak points:

A simple mitigation: strip code fences defensively before parsing.

function extractJson(text) {
  const cleaned = text.trim()
    .replace(/^```json\n?/, '')
    .replace(/^```\n?/, '')
    .replace(/```$/, '');
  return JSON.parse(cleaned);
}

Method 2: Prefilling the assistant response

Prefilling means you seed the start of the assistant's reply so Claude has to continue naturally into JSON rather than deciding how to format it. You set the assistant's first message content to { and Claude continues from there, since the model is strongly biased to produce a coherent continuation.

{
  "model": "claude-sonnet-4-5",
  "max_tokens": 1024,
  "system": "Respond with JSON matching this schema: {\"summary\": string, \"tags\": string[]}",
  "messages": [
    { "role": "user", "content": "Summarize this ticket: ..." },
    { "role": "assistant", "content": "{" }
  ]
}

Claude will complete the object starting from {, which eliminates the code-fence problem almost entirely. You then just prepend the { back when parsing.

Prefilling is a good middle ground: it's cheap, requires no extra schema infrastructure, and significantly improves reliability over plain prompting.

Method 3: Tool use for guaranteed structure (recommended)

The most robust approach is not actually "JSON mode" at all — it's tool use. You define a tool with an input_schema, and instead of generating free text, Claude calls the tool with arguments that match your schema exactly. This is the closest thing Claude has to OpenAI's structured output guarantee, because the API enforces the schema on the model's output.

const response = await fetch("https://api.subtoapi.app/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-5",
    max_tokens: 1024,
    tools: [{
      name: "extract_product",
      description: "Extract structured product data",
      input_schema: {
        type: "object",
        properties: {
          name: { type: "string" },
          category: { type: "string" },
          price_usd: { type: "number" },
          in_stock: { type: "boolean" }
        },
        required: ["name", "category", "price_usd", "in_stock"]
      }
    }],
    tool_choice: { type: "tool", name: "extract_product" },
    messages: [
      { role: "user", content: "Wireless mouse, electronics, $24.99, currently available." }
    ]
  })
});

const data = await response.json();
const toolUse = data.content.find(c => c.type === "tool_use");
console.log(toolUse.input); // { name, category, price_usd, in_stock }

Setting tool_choice to force a specific tool means Claude has no choice but to produce arguments matching that schema — no stray prose, no markdown fences, no "Sure, here's the JSON:" preamble. This is why most production teams doing data extraction with Claude use tool use rather than prompt-based JSON instructions.

The tradeoff is a slightly more verbose request/response shape: you parse content[].tool_use.input instead of raw text. But for anything feeding a database, a form, or another API, that tradeoff is worth it.

If you're routing requests through SubToAPI, this same tool-use flow works unchanged — point your existing code at api.subtoapi.app with your sub_live_... key, and every structured-output call is logged with full token and cost metadata in your dashboard. See the tool use docs and messages API docs for the full schema reference.

Validating output before you trust it

Even with tool use, add a validation layer — schemas constrain shape but not always business logic (e.g., price_usd could technically be 0 or negative if your schema doesn't say minimum: 0). Use a JSON Schema validator like ajv in Node or jsonschema in Python to double-check before writing to your database:

import Ajv from "ajv";
const ajv = new Ajv();
const validate = ajv.compile(productSchema);
if (!validate(toolUse.input)) {
  console.error(validate.errors);
}

Choosing the right method

If you're building anything that touches production data, start with tool use. It's barely more code and removes an entire category of parsing bugs.

Getting started

SubToAPI gives you a standard HTTPS endpoint for all of this — streaming, tool use, and structured extraction all work exactly like the native Anthropic API, but with API keys, usage tracking, and team billing built in. Check the quickstart guide or sign up for a free trial to try structured output calls against your own account. Plans start at €9/month on the pricing page.

Questions

Does Claude have a response_format: json parameter like OpenAI? No. Claude has no dedicated JSON mode flag. You get structured output through system-prompt instructions, assistant message prefilling, or — most reliably — tool use with a defined input schema.

What's the most reliable way to force valid JSON from Claude? Define a tool with a strict input_schema and set tool_choice to force that tool. Claude then returns schema-conformant arguments instead of free text, eliminating stray prose and markdown fences.

Can I use JSON structured output with streaming responses? Yes, but tool-use arguments arrive as streamed JSON deltas that you need to buffer and parse once complete. For strict single-object outputs, non-streaming tool calls are simpler to validate; see the streaming docs for the event format.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →