Summary
When JSON.parse() or json.loads() crashes in production with SyntaxError: Unexpected token or Unterminated string in JSON on an LLM response, the model either wrapped the JSON in markdown fences (```json), hit max_tokens mid-object, or used loose JSON mode instead of strict json_schema.
If you want this hardened cleanly, SazM fixes broken LLM structured-output pipelines for a fixed $99, delivered within 48 hours, 100% in writing with zero calls. See our AI integration services or request the $99 fix.
1. Use json_schema (strict: true) Over Plain json_object
- Plain
json_objectonly guarantees valid JSON syntax, not your field names or types. - Use
response_format: { type: "json_schema", json_schema: { ..., strict: true } }(or tool-calling with strict schema) and validate with Zod/Pydantic.
2. Guard Against finish_reason === "length"
- If
finish_reasonislength, the JSON was truncated bymax_tokens—raisemax_tokensor fail over cleanly instead of passing truncated text toJSON.parse().
Need It Fixed?
We debug production OpenAI, Anthropic, and Cloudflare Workers AI structured-output pipelines—plus our 5-tool MCP server (sazm.in/mcp)—for a fixed $99 within 48 hours, verified before you pay and 100% async. Start your $99 fix or explore our AI integration services.