The short answer
#The model has learned from millions of chat conversations where code, including JSON, is shown inside fenced code blocks, so it does the same for you. You can strip the fences before calling JSON.parse, which is a fine stopgap. The proper fix is to tell the API what shape you want with structured outputs, after which there is nothing to strip.
_10function stripFences(raw: string): string {_10 // \x60 is a backtick. Match an opening fence, an optional language label, the body, and the closing fence._10 const match = raw.match(/\x60{3}\w*\s*([\s\S]*?)\x60{3}/);_10 return (match ? match[1] : raw).trim();_10}_10_10const data = JSON.parse(stripFences(text));
Why it happens
#Models that power chat products are trained on a huge amount of text in which code is formatted the way developers format it on the web: fenced with three backticks and labelled with a language. When the model decides the thing it is about to write is code, the fence comes with it, because that is the most likely way for code to appear. JSON looks like code, so it gets the treatment.
The fences are also useful to the model's usual audience. In a chat window, a fenced block gets syntax highlighting and a copy button. The model has no way of knowing that this time the reader is JSON.parse rather than a person, unless you tell it, and even when you tell it the habit is strong. The same mechanism produces the friendly preamble: "Here is the JSON you asked for:" followed by the object. In a conversation that is polite. In your code it is a SyntaxError from JSON.parse complaining about an unexpected token.
How to fix it
#Strip the fences before parsing
If you already have a working prompt and just need it to stop breaking, clean the string first. Pull out the body of a fenced block if there is one, otherwise use the raw text.
_12function extractJson(raw: string): string {_12 const fenced = raw.match(/\x60{3}\w*\s*([\s\S]*?)\x60{3}/);_12 const body = fenced ? fenced[1] : raw;_12_12 // Also drop any prose before the first brace or bracket and after the last one._12 const start = body.search(/[{[]/);_12 const end = Math.max(body.lastIndexOf('}'), body.lastIndexOf(']'));_12 if (start === -1 || end === -1 || end < start) {_12 throw new Error('No JSON object or array found in response');_12 }_12 return body.slice(start, end + 1);_12}
Wrap the call in a try block. JSON.parse throws on anything it cannot read, and you want that to become a logged error with the raw text attached rather than a crash. Treat this as the fallback layer, not the plan.
Also handle the leading prose
The second half of extractJson above deals with "Here is the JSON:" and with a closing remark like "Let me know if you need anything else." It finds the first { or [ and the last } or ] and keeps what is between them. This is good enough for a single object or array. It will go wrong if the prose itself contains a brace, which is uncommon but possible, so keep the error path.
Use structured outputs (the right fix)
Instead of asking for JSON and then cleaning up, give the API a schema. The response is constrained to match it: no fences, no preamble, every key present and typed. In the Anthropic SDK that is output_config.format.
_26import Anthropic from '@anthropic-ai/sdk';_26_26const client = new Anthropic();_26_26const response = await client.messages.create({_26 model: 'claude-haiku-5-5',_26 max_tokens: 256,_26 messages: [{ role: 'user', content: `Extract the sender and subject from this email:\n\n${email}` }],_26 output_config: {_26 format: {_26 type: 'json_schema',_26 schema: {_26 type: 'object',_26 properties: {_26 sender: { type: 'string' },_26 subject: { type: 'string' },_26 },_26 required: ['sender', 'subject'],_26 additionalProperties: false,_26 },_26 },_26 },_26});_26_26const block = response.content.find((b) => b.type === 'text');_26const data = block?.type === 'text' ? JSON.parse(block.text) : null;
If you use Zod, zodOutputFormat from @anthropic-ai/sdk/helpers/zod with client.messages.parse() does the same and hands back a typed parsed_output. Either way the regex becomes unnecessary. Most providers now offer some form of schema-constrained output; check your provider's docs for the exact option name.
Why prefill no longer works
You may find older advice telling you to start the assistant's reply for it: send a final message with role: 'assistant' and content: '{', so the model has to continue from an open brace and cannot begin with a fence or a sentence. This was a reasonable trick for its time. Current Anthropic models do not accept it: a request that ends with an assistant message is rejected with a 400 error. Structured outputs replace the trick and give you a stronger guarantee than a single opening brace ever did.
Common pitfalls
#- A regex that only matches the
jsonlabel. The model sometimes writes a bare fence, or labels itjavascript. Make the label optional and match any word, as the examples above do. - Stripping fences and nothing else. "Here is your data:" survives a fence-only regex. Handle the prose too, or move to structured outputs.
- Parsing without a
try****. A single malformed response should produce a logged error and a retry, not take down the request. Keep the raw text in the log so you can see what the model actually sent. - Asking for JSON in the system prompt and assuming that is enough. It reduces the problem; it does not remove it. The fence habit is strong and shows up on exactly the request you did not test.
- Cleaning the output when the real problem is truncation. If
stop_reasonismax_tokens, the JSON is cut off, and no amount of regex will repair it. Raisemax_tokens.
Related reading
#quick question
Was this resource helpful?
by Danny