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:
- Strips a leading/trailing code fence.
- Runs
JSON.parseinside atry/catch. - 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.parseinside 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 withArray.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.