/n8n-tutorials

How to fix “JSON parse error” after malformed model output in n8n?

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

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to fix “JSON parse error” after malformed model output in n8n?

The fastest, most reliable fix is to never trust the model to produce perfect JSON. Instead, wrap the model output with a Function or IFFunction 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.

 

Why this happens

 

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.

 

The practical production fix

 

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)
  }
];

 

How this protects your workflow

 

  • This node prevents runtime crashes in downstream nodes by ensuring malformed JSON is either repaired or wrapped in a safe object.
  • If JSON is unrecoverable, you still return a valid object with \_error: true, which keeps the workflow running and allows you to make decisions (branching, retries, notifications).
  • Downstream nodes like IF or Switch can now check for $json.\_error instead of failing hard.

 

Optional: make the LLM more predictable

 

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.

 

Production tip: enable error workflows

 

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.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022