DEV Community

Viktornovakuae
Viktornovakuae

Posted on

How to Fix Broken LLM JSON in n8n, Python & Node.js in Under 5ms (Without Expensive Retries)

If you build AI agents in n8n, Make.com, LangChain, or plain Python/Node.js, you have definitely seen SyntaxError: Unexpected token break a production workflow.

Even with strict system prompts, LLMs frequently wrap JSON in prose or markdown fences, leave trailing commas, use single quotes, or slip in Python literals (True, False, None). Retrying the LLM call wastes tokens and adds 2–5 seconds of latency. Instead, you can sanitize and repair malformed LLM output deterministically at the edge in under 5ms.

One-Call Fix via Edge Micro-API

I built a lightweight Cloudflare Workers micro-API specifically for this workflow glue: LLM JSON Repair & Sanitizer API on RapidAPI (also available on Zyla API Hub).

It automatically:

  • Strips surrounding conversational text and markdown fences
  • Removes // and /* */ comments
  • Quotes unquoted object keys (city: -> "city":)
  • Converts single-quoted strings to valid double-quoted JSON
  • Normalizes Python True / False / None to true / false / null
  • Strips trailing commas before } and ]

Example in Node.js

const res = await fetch(
  "https://llm-json-repair-sanitizer.p.rapidapi.com/v1/json/repair",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-rapidapi-key": process.env.RAPIDAPI_KEY,
      "x-rapidapi-host": "llm-json-repair-sanitizer.p.rapidapi.com",
    },
    body: JSON.stringify({
      text: "Here is JSON:\n{ city: 'Dubai', live: True, }",
    }),
  }
);

const data = await res.json();
console.log(data.repaired); // { city: "Dubai", live: true }
Enter fullscreen mode Exit fullscreen mode

Example in n8n

Drop an HTTP Request node right after your AI Agent / OpenAI node:

  • Method: POST
  • URL: https://llm-json-repair-sanitizer.p.rapidapi.com/v1/json/repair
  • Body (JSON): { "text": "={{ $json.output }}" }
  • Pass {{ $json.repaired }} straight into PostgreSQL, Airtable, or HubSpot with zero crashes.

More Sub-20ms Edge Micro-APIs for AI & n8n Workflows

Top comments (0)