Learn how to fix JSON parse errors in n8n caused by malformed model output with clear steps to troubleshoot and clean your data.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
The fastest, most reliable fix is to never trust the model to produce perfect JSON. Instead, wrap the model output with a Function or IF → Function step that tries JSON.parse() safely, catches errors, cleans the text, and only then parses it. This prevents the workflow from crashing when the LLM returns malformed JSON.
LLM nodes sometimes output things like trailing commas, missing quotes, or extra text around JSON. The next n8n node (usually a Set, IF, Code, or any node expecting JSON data) tries to parse that as valid JSON and fails. n8n itself does not “auto-repair” bad JSON — so you must validate or sanitize it before letting it reach the node that depends on correct structure.
Put a Function node immediately after your AI model node. Use a safe parse pattern: try to parse; if it fails, try cleanup; if still fails, fail gracefully and send a useful error payload rather than crashing the workflow.
// This runs in an n8n Function node
const raw = $json.output || ""; // adjust "output" to match your AI node field
function safeParse(str) {
try {
return JSON.parse(str);
} catch (e) {
// Attempt common cleanups
let cleaned = str.trim();
// Remove code fences like ```json ... ```
cleaned = cleaned.replace(/```[\s\S]*?```/g, '').trim();
// Remove leading or trailing text before/after braces
const firstBrace = cleaned.indexOf("{");
const lastBrace = cleaned.lastIndexOf("}");
if (firstBrace !== -1 && lastBrace !== -1) {
cleaned = cleaned.slice(firstBrace, lastBrace + 1);
}
try {
return JSON.parse(cleaned);
} catch (e2) {
// Last resort: send structured error message
return {
_error: true,
message: "Model returned invalid JSON",
raw: str
};
}
}
}
return [
{
json: safeParse(raw)
}
];
In your model prompt, tell the model explicitly to return JSON only, and to wrap it with no explanations. This doesn’t guarantee perfection, but reduces risk.
Return ONLY valid JSON.
Do not add comments, code fences, or explanation text.
If a parse error still slips through upstream nodes, configure an error workflow in n8n. This gives you a safety net: alerts, logging, rerun logic, etc.
Final note: JSON parse errors are normal when working with LLMs. The fix is to never assume valid JSON. Always validate or repair the text in a controlled Function node before you hand it to the rest of your workflow.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.