← Blog

Claude API Structured JSON Output Parsing Guide

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

Why structured JSON output is hard with LLMs

If you're building anything beyond a chatbot, you need Claude to return data your code can consume directly: a parsed invoice, a classification label, a list of extracted entities. The problem is that Claude is a text model — by default it returns prose, and prose is not JSON. Even when you ask nicely for "JSON only," you can get markdown code fences, trailing commentary, or JSON that's almost valid but has a trailing comma or an unescaped quote.

This article covers the three practical approaches that actually produce reliable structured output from the Claude API — prompting conventions, tool/function-call schemas, and post-processing validation — plus how to handle the failure cases that will inevitably show up in production.

Approach 1: Prompt-only JSON (fast, but fragile)

The simplest method is to instruct Claude to respond with JSON matching a shape you describe in the prompt:

You are a data extraction engine. Given the input text, return ONLY a JSON object
with this exact shape, no markdown, no explanation:
{"name": string, "email": string, "company": string|null}

This works most of the time with Claude 3.x models, especially if you:

The downside: there's no hard guarantee. A model update, an edge case in the input, or a long conversation history can produce output that doesn't parse. You should never call JSON.parse() directly on a prompt-only response in production without a fallback.

Approach 2: Tool use / function calling (recommended for reliability)

Claude's tool-use feature is the closest thing to a schema contract the API offers. Instead of asking Claude to "write JSON," you define a tool with a JSON Schema input, and Claude returns a tool_use block whose input field is already a structured object — not a string you need to parse out of surrounding text.

{
  "name": "extract_contact",
  "description": "Extract contact details from text",
  "input_schema": {
    "type": "object",
    "properties": {
      "name": { "type": "string" },
      "email": { "type": "string" },
      "company": { "type": ["string", "null"] }
    },
    "required": ["name", "email"]
  }
}

When Claude decides to call this tool, the response includes a content block of type tool_use with an input object that already conforms to the schema's types — no markdown stripping, no regex to pull JSON out of a sentence. This is the method to reach for whenever structure matters more than conversational flexibility, and it's the same mechanism used for agent-style function calling.

If you're calling Claude through SubToAPI, tool definitions work the same way against the /v1/messages endpoint — you pass tools and a tool_choice, and the returned tool_use block is already structured JSON on your side. See /docs/tools for the request/response shape and /docs/messages for the base message format.

Approach 3: Streaming and partial JSON

If you're streaming responses (for UI responsiveness or long outputs), structured output gets trickier because you receive the JSON in chunks, not as one blob. Two patterns handle this:

  1. Buffer then parse — accumulate the full stream, then parse once at the end. Simple, but you lose the latency benefit of streaming for structured data.
  2. Incremental JSON parsing — use a streaming-tolerant JSON parser (e.g. a "partial JSON" library) that can parse an in-progress object and expose fields as they become valid, so your UI can render name before email has arrived.

For tool-use streaming specifically, Claude emits input_json_delta events that are fragments of the input field being built up — you concatenate the string fragments and parse once the tool_use block closes. SubToAPI exposes the same event stream over SSE; details are in /docs/streaming.

Validating what comes back

Even with tool schemas, treat the response as untrusted input — a model can still return a string where you expected a number, or omit an optional-but-expected field. Validate before you use it:

import { z } from "zod";

const ContactSchema = z.object({
  name: z.string(),
  email: z.string().email(),
  company: z.string().nullable(),
});

function parseClaudeOutput(toolInput) {
  const result = ContactSchema.safeParse(toolInput);
  if (!result.success) {
    // log, retry, or fall back to a repair prompt
    throw new Error("Schema validation failed: " + result.error.message);
  }
  return result.data;
}

This pattern — schema-constrain with tools, then validate with a library like Zod, Pydantic, or ajv — is the most robust combination available today. Neither step alone is sufficient: tool schemas reduce drift but don't guarantee semantic correctness (a valid-shaped email field can still contain garbage), and validation alone can't fix malformed JSON if you're not using tool use.

Handling malformed JSON gracefully

For prompt-only JSON that fails to parse, don't just retry blindly — that doubles your cost for the same failure mode. Instead:

In practice, switching from prompt-only JSON to tool-use schemas eliminates the vast majority of these repair cycles, so it's worth the upfront schema-writing cost for any endpoint that's called more than a handful of times.

Keeping this in production

Once your extraction pipeline works, the operational side matters just as much as the parsing logic: rotating keys safely, tracking which endpoint or team member is burning through usage, and giving non-engineers visibility without handing out your main Anthropic credentials. SubToAPI wraps Claude access in application-scoped sub_live_... keys with per-key usage metadata, so you can issue a separate key to your extraction service and see exactly how much of your spend comes from it. Start with a free trial at /signup, check plan details at /pricing, or jump straight to /docs/quickstart to wire up your first structured-output call.

questions

Does the Claude API have a native "JSON mode" like some other providers? Not a dedicated response-format flag. The equivalent is tool use with a defined input_schema — Claude returns a structured tool_use block instead of free text, which serves the same purpose as JSON mode elsewhere.

Should I use tool use or prompt-only JSON for simple extraction tasks? For anything called repeatedly or feeding downstream code, use tool use — it's far less prone to drift. Prompt-only JSON is fine for prototyping or one-off scripts where you can eyeball the output.

How do I handle JSON that arrives in streaming chunks? Either buffer the full response before parsing, or use a partial-JSON parser that can read an in-progress object as input_json_delta events arrive, then do a final strict parse once the block closes.

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 →