Formatting Output (Enforcing JSON)
In the beginner course, we learned that asking Claude to output JSON is a great way to extract data. But when using the API, if Claude includes even one conversational word (like "Here is your JSON:"), your JSON.parse() method will throw an error and crash your app.
When building reliable API applications, you need bulletproof JSON generation.
The Standard Approach: System Prompts
The best way to enforce JSON is to combine a strict System Prompt with a trailing instruction in the User prompt.
System Prompt:
"You are a data extraction API. Your ONLY function is to output valid, raw JSON. You must never include conversational text, markdown formatting, or explanations. If you include any text outside the JSON object, the system will crash."
User Prompt:
"Extract the names and ages from this text. Output the JSON and nothing else: 'John is 30, Jane is 25'."
The 'Prefill' Trick
Anthropic's API has a unique superpower that makes JSON enforcement virtually guaranteed. It's called Assistant Prefilling.
Because the API accepts a list of previous messages, you can actually fake Claude's response. You can put words in Claude's mouth.
If you send this array:
messages: [
{ role: 'user', content: 'Extract the users into JSON.' },
{ role: 'assistant', content: '{ "users": [' }
]
You are telling Claude: "The user asked for JSON, and you (the assistant) have already started writing it. Now, finish the thought."
Because Claude is fundamentally a predictive text engine, it sees { "users": [ and its only logical next step is to continue writing valid JSON. It physically cannot output "Here is your JSON:" because you already forced it past that point!
Handling the Output
If you use the Prefill trick, you must remember that Claude's response will only contain the completion of the JSON.
If Claude responds with {"name": "John"}]} , you have to manually combine your prefill string with Claude's output in your code before parsing it:
const prefill = '{ "users": [';
const claudeResponse = response.content[0].text;
const finalJsonString = prefill + claudeResponse;
const data = JSON.parse(finalJsonString);
Using a strong System Prompt combined with Assistant Prefilling is the industry standard way to guarantee 100% reliable JSON extraction with Anthropic.