Make n8n parse LLM JSON reliably: the code-fence guard that stops silent failures

Most “AI in n8n” workflows pass their tests, then break in production for one boring reason: the model wraps its JSON in a markdown code fence.

You ask for { "score": 7 } and get:

```json
{
  "score": 7
}
```

Now JSON.parse($json.message.content) throws. Or worse: an expression like {{ $json.score }} quietly resolves to undefined, and the workflow keeps running on empty data. Silent is the dangerous one.

The fix is one Code node between the LLM and everything downstream. It does three things:

  1. Strips a leading/trailing code fence.
  2. Runs JSON.parse inside a try/catch.
  3. On failure, returns the raw text in a known shape instead of throwing, so you can route it to a review branch and actually see what the model said.
const raw = $input.first().json.message?.content ?? '';
const cleaned = String(raw).trim()
  .replace(/^```(?:json)?/i, '')
  .replace(/```$/, '')
  .trim();

let parsed = {};
let parse_ok = true;
try {
  parsed = JSON.parse(cleaned);
} catch (e) {
  parse_ok = false; // do not throw: keep the item alive
}

return [{ json: { parse_ok, ...parsed, _raw: parse_ok ? undefined : cleaned } }];

Then an IF node on parse_ok: true continues as normal, false logs _raw (or pings you with the bad completion).

Three things I keep seeing go wrong:

  • Not handling the fence. Strong models do it too, especially on long outputs.
  • Calling JSON.parse inside an expression. An expression that throws kills the item, and you lose the raw reply you need to debug.
  • Trusting the schema. Even valid JSON can arrive with action_items: null. Guard with Array.isArray(x) ? x : [] before you .map() it.

One prompt trick that pays for itself: ask for the strict shape and name the fallback value. E.g. “if the owner is not stated in the notes, write ‘not stated’”. It removes almost every hallucinated owner.

I use this guard in a small “meeting notes to action items” workflow: Manual Trigger → Set (notes) → OpenAI (strict JSON) → this parse+guard Code node → Set output. It returns a summary, the decisions, a Markdown table of action items with owner/due, and a draft follow-up email (plus a count of open items to branch on) - and it never dies on a bad completion.

How do you handle invalid JSON from a model: a guard like this, one automatic retry, or the AI Agent structured output? I keep flip-flopping between “guard + alert” and “guard + retry once”, so I would like to hear what has held up in production for you.

Nice guard. One subtle issue in the snippet: { parse_ok, …parsed } lets a model-supplied parse_ok overwrite your parser flag, even valid JSON like {“parse_ok”: false} could take the wrong branch

I’d check that the parsed value is a non-null object (not an array), spread it first, then write the trustd parse_ok last. For anything going into a CRM, I’d also validate the required fields before the success branch writes

1 Like

Good catch - you are right, and it is a real bug, not a nitpick.

{ parse_ok, ...parsed } puts the model’s own JSON after my flag, so a reply like {"parse_ok": false} flips the branch. The snippet also never checks the parsed shape: JSON.parse("[1,2]") returns an array, spreading it silently gives {"0":1,"1":2}, and JSON.parse("null") / JSON.parse("true") spread to nothing at all. No throw, no error - exactly the silent mode the guard is supposed to prevent.

Corrected node:

const raw = $input.first().json.message?.content ?? '';
const cleaned = String(raw).trim()
  .replace(/^```(?:json)?/i, '')
  .replace(/```$/, '')
  .trim();

let parsed = null;
let parse_ok = false;
try {
  const candidate = JSON.parse(cleaned);
  if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
    parsed = candidate;
    parse_ok = true;
  }
} catch (e) {
  // do not throw: keep the item alive for the review branch
}

return [{
  json: {
    ...(parsed ?? {}),
    parse_ok,                                  // written last on purpose
    _raw: parse_ok ? undefined : cleaned,
  },
}];

Two rules behind it:

  1. parse_ok is written after the spread, so a model-supplied key can never flip the branch.
  2. Success means “a plain, non-null object”, so arrays / null / true / a bare number all fall to the review branch instead of passing.

On validate-before-write: agreed, that is the part that actually protects the CRM. I keep the shape check in the guard, then a small valid gate before anything is written:

const item = $input.first().json;
const required = ['summary', 'action_items'];
const missing = required.filter(k => !(k in item));
const action_items = Array.isArray(item.action_items) ? item.action_items : [];
return [{ json: { ...item, missing, action_items, valid: missing.length === 0 } }];

Then the IF tests valid === true (plus action_items.length > 0 when an empty list should skip), not parse_ok. That keeps “the model answered” and “the model answered usefully” as two separate gates.

Thanks for reading the snippet closely.

I’d combine structured output with validation rather than relying on JSON parsing alone.

One edge case worth handling is valid JSON with an invalid structure.

For example, JSON.parse() might succeed, but the model could return null, an array instead of an object, or missing required fields.

I’d approach it in three stages:

  1. Request structured output from the model.

  2. Validate both the JSON syntax and expected schema before processing.

  3. If validation fails, retry once with the validation error as feedback, then route persistent failures to a review queue.

For workflows that trigger customer messages, bookings, or database changes, I’d make sure validation completes before any external action.

My background is mainly TypeScript and backend/API development, and I’m applying these patterns while building my own n8n automation projects.

One question: Are you using the AI Agent node or calling the model directly? That would influence where I’d put the validation and retry logic.

Direct model call, not the AI Agent node - and the reason is exactly the question of where validation goes.

The Agent node wraps the model in a tool-calling loop. That is great when the model has to decide which tools to call, but it makes the output shape less predictable and hides the retry logic inside a loop you do not control. For a formatting contract like ‘return this JSON’, I want one deterministic completion, so I use the OpenAI node (or an HTTP Request) with a structured output / JSON schema response and no tools. Then validation is just a node right after it.

If you do use the Agent node, I would still keep validation outside it and make the retry an explicit loop on the canvas: IF validation fails, re-call with the validation error appended, max 1 retry. Same three stages you described, only the loop is visible instead of hidden inside the agent.

Two things I would add to your stages:

  1. Structured output (json_schema / strict mode) removes the code-fence problem at the source, so validation becomes the second gate, not the first. But strict mode still allows a valid-but-useless object - an empty array, a null for an optional field - so the schema check must cover required fields and types, not just ‘did it parse’.

  2. The retry is another model call: more tokens, more latency, not deterministic. Bound it at 1, and log both attempts (raw text plus the validation error) so you can tell a flaky model from a bad prompt. And your rule that validation completes before any external action is the one I would treat as non-negotiable - the ordering is validate then act, never act then validate.

Good to hear you are bringing backend/TS habits into n8n; the schema discipline carries over almost 1:1. How do you shape the retry today - a sub-workflow that returns a valid flag, or an IF node with two branches?

Enforcing structural code-fence guards and strict schema validation boundaries is the only way to eliminate non-deterministic JSON schema drifts within enterprise n8n workflows. When a frontier LLM drops ungrounded markdown wrappers or unexpected syntax fragments under peak load spikes, the standard parsing layers collapse into silent system drops.

To permanently secure your data-transit edge, I wrap incoming model payloads inside hardcoded Pydantic validation gates and stateful error-handling sub-graphs before passing the variables to the execution runner. For high-throughput transactional syncs, combining these code-fence safeguards with native Redis lock primitives (INCR + TTL gates) completely isolates the state machine, maintaining a 99.99% operational runtime uptime without duplicate mutations.

I’ve detailed my exact fault-tolerant parsing configurations, crash-proof n8n topologies, and Gemini adapter patches straight on my GitHub profile homepage for technical review: https://github.com. Prevention is always superior to tracking silent regressions!