Skip to main content
AI JSONMedic
By The JSON Medic··14 min readn8nworkflow automationJSON errorsAI agents

Fixing n8n JSON Parse Errors: A Practical Guide for Workflow Builders

n8n AI node returning malformed JSON? Fix the 6 patterns that break automations — truncated output, trailing commas, Python literals — with exact node fixes you can paste in now.

Have broken JSON right now? Fix it free in under 1 second — no signup.

Fix My JSON →

If you're building AI-powered workflows in n8n and running into JSON parse errors, you're dealing with one of the most frustrating failure modes in automation: a workflow that works 80% of the time and fails silently the other 20%.

This guide covers the specific JSON errors that break n8n workflows and how to fix them, both manually and with automated repair logic.

Why n8n JSON Errors Are Uniquely Painful

n8n is a workflow automation tool that chains together HTTP requests, AI calls, and data transformations. When an AI node (like the OpenAI or Anthropic node) returns malformed JSON, the workflow either:

  • Throws a "JSON parse error" and stops completely
  • Passes the raw broken string downstream, silently corrupting subsequent nodes

The second case is worse. You might not notice for hours that your database has been receiving garbage data.

The Most Common n8n JSON Error Patterns

AI Node Returns Markdown-Wrapped JSON

The most common failure: your OpenAI or Claude node returns:

json

{"status": "success", "items": [...]}

n8n's built-in JSON parser fails immediately because the backtick fences aren't JSON. The fix: strip the markdown before parsing.

In n8n, you can use a Code node with this snippet:

const raw = $input.first().json.output;
const stripped = raw.replace(/^
json\s/i, '').replace(/\s```$/, '').trim();

return [{ json: JSON.parse(stripped) }];


### Truncated AI Response

When your prompt asks the AI to return a large JSON object, the response may be cut off at the token limit:
json

{

"products": [

{"id": 1, "name": "Widget A", "price": 9.99},

{"id": 2, "name": "Widget B"


This causes a parse error in any downstream node that tries to process the JSON.

**Prevention:** Break large JSON requests into smaller batches. Ask the AI to return one item at a time and loop.

**Recovery:** Use AI JSONMedic's API endpoint to repair the truncated JSON before parsing:
javascript

const res = await fetch('https://aijsonmedic.com/api/repair', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ input: brokenJson }),

});

const { output } = await res.json();

return [{ json: JSON.parse(output) }];


### Trailing Commas from AI Structured Output

AI models frequently produce:
json

{

"name": "Alice",

"role": "admin",

}


Note the trailing comma after `"admin"`. JSON.parse throws `Unexpected token }`. Fix with a regex in a Code node:
javascript

const fixed = raw

.replace(/,(\s*[}\]])/g, '$1'); // remove trailing commas

return [{ json: JSON.parse(fixed) }];


### Python Literals in JSON

If you're using an AI to process Python-heavy data or calling a Python-based tool, you may receive:
json

{"active": True, "deleted": False, "value": None}


These are Python keywords, not JSON keywords. Fix:
javascript

const fixed = raw

.replace(/\bTrue\b/g, 'true')

.replace(/\bFalse\b/g, 'false')

.replace(/\bNone\b/g, 'null');

return [{ json: JSON.parse(fixed) }];


## Building a Resilient JSON Parse Node in n8n

The most reliable approach is a reusable Code node at the start of every AI workflow branch that handles all common repair patterns:
javascript

function repairJson(raw) {

let s = raw;

// Strip markdown fences

s = s.replace(/^``(?:json)?\s*/im, '').replace(/\s*``\s*$/m, '').trim();

// Extract first { or [ block

const start = s.search(/[{[]/);

const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']'));

if (start !== -1 && end !== -1) s = s.slice(start, end + 1);

// Python literals

s = s.replace(/\bTrue\b/g, 'true')

.replace(/\bFalse\b/g, 'false')

.replace(/\bNone\b/g, 'null');

// Trailing commas

s = s.replace(/,(\s*[}\]])/g, '$1');

return s;

}

const raw = $input.first().json.text ?? $input.first().json.output ?? '';

const repaired = repairJson(raw);

try {

return [{ json: JSON.parse(repaired) }];

} catch (e) {

// Return raw for debugging rather than crashing silently

return [{ json: { _parseError: e.message, _raw: repaired } }];

}


This node never throws. It either parses successfully or returns the raw string with an error flag, letting your workflow handle the failure gracefully.

## Using AI JSONMedic's API in n8n

For production workflows where repair quality matters, you can call [AI JSONMedic's JSON repair tool](/json-repair) or its API from an HTTP Request node:

1. Add an **HTTP Request** node after your AI node
2. Set Method to `POST`, URL to `https://aijsonmedic.com/api/repair`
3. Set body to: `{"input": "{{$json["text"]}}"}`
4. The response contains `output` (repaired JSON string) and `issues` (array of what was fixed)

This offloads repair logic from your workflow and handles edge cases the simple regex approach misses (like truncation and complex quote escaping).

## Setting Up Error Handling in n8n (Try/Catch Nodes)

n8n has a built-in error handling system that lets you catch failures and route them to a recovery branch. This is the right architecture for handling JSON parse errors in production workflows.

### Using the Error Trigger Node

The simplest approach is to connect an **Error Trigger** node to any node that might fail. When a JSON parse error occurs:

1. The failing node throws an error
2. n8n catches it and routes execution to the Error Trigger branch
3. Your recovery branch can log the error, send an alert, or retry with a repair step

To set this up:
- Open your workflow settings (gear icon)
- Under "Error Workflow", select or create a dedicated error-handling workflow
- In that workflow, add an Error Trigger node as the starting point

### Building a Try/Catch Pattern with a Code Node

For inline error handling (without a separate error workflow), use a Code node that wraps your parse logic in a try/catch and routes based on success:
javascript

const raw = $input.first().json.text ?? $input.first().json.output ?? '';

let parsed = null;

let error = null;

try {

// Attempt repair + parse

let s = raw

.replace(/^```(?:json)?\s*/im, '')

.replace(/\s```\s$/m, '')

.trim();

s = s.replace(/,(\s*[}\]])/g, '$1');

parsed = JSON.parse(s);

} catch (e) {

error = e.message;

}

return [{

json: {

success: parsed !== null,

data: parsed,

error: error,

raw: parsed === null ? raw : undefined,

}

}];


Then add an **IF node** after this Code node that checks `{{ $json.success }}`. The true branch continues your workflow. The false branch handles the failure, whether that means retrying, alerting, or skipping.

### Using n8n's Built-In "Continue on Error" Setting

For less critical workflows, you can set individual nodes to continue on error rather than stop the workflow:

- Click any node to open its settings
- Go to the **Settings** tab
- Toggle "Continue On Error" to on

When enabled, the node passes an error object downstream instead of stopping execution. You can inspect `{{ $json.error }}` in downstream nodes to check whether the previous step succeeded.

## n8n HTTP Request Node JSON Error Debugging

The HTTP Request node is a common source of JSON errors in n8n, separate from AI nodes. Here's how to debug it.

### The "Response Content-Type Mismatch" Problem

When an API returns JSON but sets the wrong `Content-Type` header (e.g., `text/plain` instead of `application/json`), n8n passes the response as a raw string rather than a parsed object. You then get a string where you expected an object.

Fix: in the HTTP Request node settings, set **Response Format** to "JSON" explicitly. This forces n8n to parse the body regardless of Content-Type.

### The Empty Response Problem

Some APIs return a 200 OK with an empty body, or return `null`. n8n's JSON parser throws on empty input.

Add a Code node after the HTTP Request:
javascript

const body = $input.first().json.body ?? $input.first().json ?? null;

if (!body || (typeof body === 'string' && body.trim() === '')) {

return [{ json: { _empty: true, _raw: body } }];

}

if (typeof body === 'string') {

return [{ json: JSON.parse(body) }];

}

return [{ json: body }];


### Debugging with the n8n Execution Log

When a JSON parse error occurs, n8n shows a red error badge on the failing node. Click it to see:

- The exact error message (e.g., `SyntaxError: Unexpected token } in JSON at position 42`)
- The input data that caused the failure
- The full stack trace

The position number in the error message is useful. Open the raw string in a text editor, count to that character position, and you'll find the exact location of the syntax error. For errors like [fix json unexpected token](/blog/fix-json-unexpected-token), the position is the key clue.

## Real Workflow Walkthrough: AI Data Extraction Pipeline

Here's a typical n8n workflow that pulls data from a website, sends it to an AI for structured extraction, and saves the result to Airtable. This walkthrough describes the setup and where JSON errors tend to appear.

**Workflow structure:**

1. **Schedule Trigger** - runs every hour
2. **HTTP Request** - fetches a webpage
3. **HTML Extract** - pulls the article text
4. **OpenAI node** - asks GPT to extract structured data as JSON
5. **Code node** - repairs and parses the JSON (this is where most JSON errors are caught)
6. **Airtable node** - saves the structured data

**Step 4 (OpenAI node) is the problem node.** The model returns something like:

Here is the extracted data:

{
  "title": "Product Launch",
  "date": "2024-01-15",
  "tags": ["launch", "product",],
}

This has three problems: prose before the JSON, markdown fences, and a trailing comma. The Code node at Step 5 handles all three.

**The Code node at Step 5:**
javascript

function repairAndParse(raw) {

// Extract JSON block from prose

const fenceMatch = raw.match(/``(?:json)?\s*([\s\S]*?)``/i);

let s = fenceMatch ? fenceMatch[1] : raw;

// If no fence, find the first { or [

if (!fenceMatch) {

const start = s.search(/[{\[]/);

const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']'));

if (start !== -1 && end !== -1) s = s.slice(start, end + 1);

}

// Fix trailing commas

s = s.replace(/,(\s*[}\]])/g, '$1');

return JSON.parse(s.trim());

}

const raw = $input.first().json.message?.content ?? '';

try {

return [{ json: repairAndParse(raw) }];

} catch (e) {

return [{ json: { _error: e.message, _raw: raw } }];

}

```

Step 6 (Airtable node) has an IF node before it that checks {{ !$json._error }}. Records with parse errors are routed to a Slack notification instead of Airtable.

n8n vs Make vs Zapier: JSON Error Handling Comparison

If you're deciding which automation platform to use, or migrating between them, here's how each handles JSON errors from AI nodes.

Featuren8nMake (Integromat)Zapier
Custom code nodesYes (Code node, full JS)Yes (limited JS in Tools)No (no custom code)
Try/catch in workflowYes (Error Trigger + Continue on Error)Yes (Error handler routes)Limited (Paths with filters)
Built-in JSON repairNoNoNo
Manual JSON debug viewYes (Execution log)Yes (History)Limited
API call for repairYes (HTTP Request node)Yes (HTTP module)Yes (Webhooks by Zapier)
Regex in data transformYes (Code node)Yes (Text parser module)No
Self-hostableYesNoNo
Open sourceYesNoNo
n8n wins for developers because of the Code node. You can write real JavaScript, import logic, and handle complex repair cases that Make and Zapier can't touch without an external API call. Make is middle ground. The Iterator module and error routes are more visual, and the JSON module has built-in parsing, but you can't run complex repair logic without calling an external service. Zapier is the weakest for JSON handling. There's no custom code, so you're dependent on Zapier's built-in formatter (which handles simple cases) or an HTTP call to a repair API for anything complex. See our Zapier JSON formatter guide for the best workarounds.

For AI-heavy workflows where you expect malformed JSON regularly, n8n with a Code node repair step is the strongest native option. For all three platforms, adding AI JSONMedic's JSON repair tool as an HTTP call gives you a production-grade repair step without writing your own edge-case logic. When debugging workflow JSON interactively, the JSON Studio lets you repair, diff, validate, and convert in one workspace without switching between tabs.

FAQ

Q: Why does my n8n workflow fail on some executions but not others?

AI models are non-deterministic. The same prompt can produce valid JSON 9 times and a trailing comma on the 10th. Build your repair step to run on every execution, not just when you see errors in testing.

Q: Can I fix JSON errors in n8n without a Code node?

Partially. For simple cases like Python literals, you can use the Set node with an expression that calls .replace(). But for complex repairs like truncation or multi-pattern fixes, the Code node is the right tool.

Q: How do I pass the raw AI output (not parsed) to the next node?

By default, n8n's OpenAI node tries to parse the output. To get the raw string, use the HTTP Request node to call the OpenAI API directly and read {{ $json.choices[0].message.content }}. This gives you the string before any parsing happens.

Q: The AI JSONMedic API isn't reachable from my self-hosted n8n. What do I do?

Check your network/firewall settings. If your n8n instance is on a private network, it may need an outbound rule to reach external HTTPS APIs. Alternatively, use the Code node repair function from this article as a fully local fallback.

Q: What's the best way to log JSON parse errors for later debugging?

In the false branch of your IF node (after the try/catch Code node), add an Airtable or Google Sheets node that logs the _raw field and _error message. This gives you a record of every failure you can review and use to improve your prompts.

Q: Does n8n's built-in OpenAI node handle JSON repair?

No. The node parses whatever the model returns. If it's invalid JSON, the parse fails and the workflow errors. You need to add your own repair step.

Conclusion

n8n JSON errors from AI nodes are predictable. By adding a repair step between your AI node and your first JSON-consuming node, you can eliminate nearly all parse failures.

Use the Code node approach for simple cases, the API approach for complex or high-stakes workflows, and the Error Trigger pattern for graceful failure handling. For a deeper dive into the errors themselves, see fix JSON unexpected token and how to fix ChatGPT JSON errors. If you're on Make or Zapier, the Make JSON errors guide and Zapier formatter guide have platform-specific solutions.

Still dealing with broken JSON?

Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.

Fix My JSON Free →

The JSON Medic newsletter

One JSON error and its fix, weekly, plus new guides and tools. Free.

We send a confirmation link first. Unsubscribe with one click in any mail. See the privacy policy.

Related Articles