← Blog

How to Prompt Claude for Structured Data

2026-09-25 · 5 min read · SubToAPI Team

Getting Claude to return structured data reliably comes down to three things: telling it exactly what shape you want, showing it an example, and giving it a way to fail predictably when the input doesn't fit. Claude is very good at following format instructions when they're explicit, but vague requests like "give me the data as JSON" produce inconsistent results — extra prose before the object, trailing commentary, or fields that don't match what you actually need.

This guide walks through the prompting patterns that consistently produce parseable output, when to use structured prompting versus tool use, and how to handle the edge cases that break naive implementations.

Start with an explicit schema, not a description

The most common mistake is describing the data loosely and hoping Claude infers the structure. Instead, define the exact schema in the prompt — field names, types, and whether fields are optional.

Extract the following fields from the text below and return them as JSON:

{
  "name": string,
  "email": string,
  "company": string | null,
  "role": string | null
}

Text:
"""
Hi, I'm Sarah Chen, VP of Engineering at Northwind Robotics. Reach me at sarah@northwind.io.
"""

Return only the JSON object, no other text.

This works better than "extract the name, email, and job info" because it removes ambiguity about key names, nesting, and null handling. Claude will match the schema almost exactly if you give it one.

Show one example when the format is unusual

For standard JSON, a schema is usually enough. For anything less common — pipe-delimited rows, custom XML tags, markdown tables with specific column order — include a one-shot example. Claude pattern-matches on examples more reliably than on prose descriptions of formatting rules.

Convert each product into a row in this exact format:

<product><name>Widget A</name><price>19.99</price><stock>42</stock></product>

Now convert these products:
1. Blue Mug, $8.50, 120 in stock
2. Steel Pen, $3.00, 300 in stock

Tell Claude to skip the preamble

By default, Claude often adds a short lead-in like "Here's the JSON you requested:" before the actual data. This breaks naive JSON.parse() calls. Explicitly forbid it:

Respond with only the JSON object. Do not include any explanation, markdown code fences, or introductory text.

If Claude still wraps output in triple backticks, strip them in your parsing code rather than fighting the model further — it's a cheap, reliable fix:

function extractJson(text) {
  const match = text.match(/```(?:json)?\s*([\s\S]*?)```/);
  return JSON.parse(match ? match[1] : text);
}

Use tool use / function calling for guaranteed structure

Prompting alone gets you close but not 100% reliable — Claude can still occasionally add a stray sentence or produce malformed JSON on edge cases. If your application depends on structure being correct every time, use Claude's tool use feature instead of pure prompting. You define a JSON schema as a "tool," and Claude returns arguments matching that schema rather than free text.

Tool use is the right choice when:

Prompting-only structured output is fine when:

If you're calling Claude through SubToAPI, both approaches work the same as with the native Anthropic API — the /v1/messages endpoint supports tool definitions, so you can pass a JSON schema and get back structured arguments instead of parsing raw text. See the tools documentation for the request format, or the messages docs if you're sticking with plain prompting.

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 512,
    "messages": [
      {"role": "user", "content": "Extract name and email: Sarah Chen, sarah@northwind.io"}
    ],
    "tools": [{
      "name": "extract_contact",
      "description": "Extract contact information from text",
      "input_schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "email": {"type": "string"}
        },
        "required": ["name", "email"]
      }
    }]
  }'

Handle missing or ambiguous data explicitly

Structured extraction breaks most often on incomplete input — a form with no email address, a product listing with no price. Tell Claude what to do in those cases instead of leaving it to guess:

If a field is not present in the text, set its value to null. Do not invent or infer missing values.

Without this instruction, Claude will sometimes fill gaps with plausible-sounding guesses, which is worse than an empty field because it looks correct on the surface.

Validate on your side too

Even with a strong prompt and a strict schema, add validation before you trust the output — a lightweight JSON Schema validator (Zod, ajv, pydantic) catches the rare malformed response before it reaches your database or a downstream API call. Treat Claude's structured output the same way you'd treat any external API response: parse defensively, and retry with a clarifying follow-up message if validation fails.

Putting it together

A reliable structured-output prompt has four parts: an explicit schema, an example if the format is non-standard, an instruction to suppress extra text, and clear rules for missing data. For anything mission-critical, layer tool use on top so the model is constrained to valid JSON by design rather than by instruction alone. If you're just getting started with the API, the quickstart guide walks through your first request end to end, and pricing covers the plan options if you're moving from prototype to production.

questions

Does asking Claude nicely for JSON guarantee valid JSON every time? No. Prompting alone gets you very close but occasional formatting slips happen, especially on long or unusual inputs. For guaranteed valid structure, use tool use / function calling instead of relying on prompt instructions alone.

Should I use tool use or prompt-only formatting for structured data? Use tool use when a downstream system depends on correct structure (database inserts, API calls). Use prompt-only formatting for simple, human-reviewed, or prototype use cases where occasional minor deviations are acceptable.

How do I stop Claude from adding extra text before or after the JSON? Explicitly instruct it to return only the JSON object with no explanation or code fences, and strip markdown fences defensively in your parsing code as a fallback.

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 →