Fix Broken Markdown Tables in ChatGPT and Claude Output
By VeloForge Labs · · 8 min read
Quick answer: LLM tables usually break for one of six reasons: no delimiter row, a delimiter row with the wrong cell count, a code fence around the table, a blank line inside it, an unescaped pipe, or a line break in a cell. Repair the text before you render it.
TL;DR: Markdown tables are strict. One missing line and the whole table shows up as a paragraph full of pipes. Below are the six problems we see most in model output, what the GitHub Flavored Markdown (GFM) spec says about each, and a small JavaScript function that fixes five of them. We ran every example with marked 18.4.0 (GFM on), the parser TexToolsAI uses.
Why do LLM tables break?
Tables are not part of plain CommonMark. They come from the GFM extension, and the GFM spec (section "Tables (extension)") has firm rules. A table needs a header row, then a delimiter row, then body rows. The spec says the delimiter row "consists of cells whose only content are hyphens (-)", with optional colons for alignment.
A language model writes the table one token at a time. It can skip the delimiter row, count columns wrong, or wrap the whole thing in a code block "to be helpful". A person would spot it. The parser does not guess, so it falls back to plain text.
Also check that GFM is on at all. In marked it is on by default. In react-markdown you add remark-gfm, whose docs list tables among the features it adds. In our test, react-markdown without it printed the table as a paragraph.
The six common problems
1. The delimiter row is missing
| Name | Qty |
| Apple | 3 |
Without the |---|---| line, marked returned a single <p> holding all the pipes. This is also what you see while a table is still streaming in: until the delimiter row arrives, the header row is just text.
2. The delimiter row has the wrong number of cells
| Name | Qty | Price |
|---|---|
| Apple | 3 | 1.20 |
The spec is clear: "The header row must match the delimiter row in the number of cells. If not, a table will not be recognized." marked returned a paragraph here too. Models do this when they add a column to the header and forget the line below it.
3. The table is inside a code fence
Models sometimes wrap tables in a fenced block marked markdown. The parser then does what it should: it shows the raw source as code, inside <pre><code>. The fix is to remove the fence.
4. A blank line splits the table
The spec says "The table is broken at the first empty line". In our run, one blank line before the last row left a two-row table followed by a stray paragraph | Pear | 5 |.
5. A pipe inside a cell
A shell command like `a | b` inside a cell adds a cell border in the middle of the code. marked split it into `a and b` and dropped the last cell, because, as the spec says, when a row has more cells than the header "the excess is ignored". The spec's fix: "Include a pipe in a cell's content by escaping it, including inside other inline spans". So write `a \| b`. With the backslash, marked rendered <code>a | b</code> in one cell.
6. A line break inside a cell
Each table row must sit on one line. When a model puts a newline inside a cell, the text after it becomes a new row. In our test, red and and sweet ended up in two different rows. The function below does not try to fix this, because it cannot tell a broken cell from a real new row. Ask the model to keep each row on one line instead.
Rows with too few cells are fine. The spec says "empty cells are inserted", and marked did that.
A tested function to repair tables
This function works on the Markdown text before you parse it. It removes markdown code fences that hold only a table, drops blank lines inside a table, adds a missing delimiter row, rebuilds a delimiter row with the wrong cell count (it keeps yours, alignment colons and all, when the count is right), escapes pipes inside code spans in table rows, and adds a blank line before the table. It leaves other code blocks alone.
const ROW = /^\s{0,3}\|.*\|\s*$/;
const DELIM = /^\s{0,3}\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
const FENCE = /^\s{0,3}(`{3,}|~{3,})\s*([\w-]*)\s*$/;
// Escape "|" inside `code spans` so it is not read as a cell border.
function escapeCodePipes(line) {
return line.replace(/`[^`]*`/g, (span) => span.replace(/(?<!\\)\|/g, "\\|"));
}
function cells(line) {
return line.trim().replace(/^\|/, "").replace(/(?<!\\)\|$/, "").split(/(?<!\\)\|/);
}
function isRow(line) {
return ROW.test(line) && !DELIM.test(line);
}
export function repairTables(markdown) {
const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
// Pass 1: unwrap ```markdown fences that hold only table lines.
const unwrapped = [];
for (let i = 0; i < lines.length; i++) {
const open = lines[i].match(FENCE);
if (open && /^(markdown|md)?$/i.test(open[2])) {
const end = lines.findIndex((l, j) => j > i && l.trim().startsWith(open[1]));
const body = end > i ? lines.slice(i + 1, end) : [];
if (body.length > 0 && body.every((l) => ROW.test(l) || DELIM.test(l))) {
unwrapped.push(...body);
i = end;
continue;
}
}
unwrapped.push(lines[i]);
}
// Pass 2: repair each run of table rows, skipping other code fences.
const out = [];
let inFence = null;
for (let i = 0; i < unwrapped.length; i++) {
const line = unwrapped[i];
const fence = line.match(FENCE);
if (fence && (!inFence || line.trim().startsWith(inFence))) {
inFence = inFence ? null : fence[1];
out.push(line);
continue;
}
if (inFence || !isRow(line)) {
out.push(line);
continue;
}
// A table starts here. Collect its rows.
const header = escapeCodePipes(line.trim());
const width = cells(header).length;
const body = [];
let delim = "|" + " --- |".repeat(width);
let j = i + 1;
if (DELIM.test(unwrapped[j] ?? "")) {
// Keep the model's delimiter row (and its alignment) only if the cell count matches.
if (cells(unwrapped[j]).length === width) delim = unwrapped[j].trim();
j++;
}
while (j < unwrapped.length) {
if (isRow(unwrapped[j])) {
body.push(escapeCodePipes(unwrapped[j].trim()));
j++;
} else if (unwrapped[j].trim() === "" && isRow(unwrapped[j + 1] ?? "") && !DELIM.test(unwrapped[j + 2] ?? "")) {
j++; // blank line inside the table: drop it
} else break;
}
if (body.length === 0 && !DELIM.test(unwrapped[i + 1] ?? "")) {
out.push(line); // a single pipe line is not a table
continue;
}
if (out.length > 0 && out[out.length - 1].trim() !== "") out.push(""); // blank line before the table
out.push(header, delim, ...body);
i = j - 1;
}
return out.join("\n");
}
Use it right before your Markdown step:
import { marked } from "marked";
import { repairTables } from "./repair-tables.js";
const html = await marked.parse(repairTables(modelOutput), { gfm: true });
// Then sanitize html before you render it.
What we tested
We ran nine inputs through repairTables and then marked 18.4.0, and counted the tables and rows in the HTML:
| Input | Before the fix | After the fix |
|---|---|---|
| Missing delimiter row | paragraph | table, 3 rows |
```markdown fence around a table |
code block | table, 2 rows |
| Delimiter row with 2 cells, header with 3 | paragraph | table, 2 rows |
| Blank line before the last row | table plus stray text | one table, 3 rows |
| Unescaped pipe inside a code span | last cell lost | correct 2 cells |
| Two real tables with a blank line between | 2 tables | still 2 tables |
Pipes inside a ```js block |
code block | unchanged |
Prose with a pipe (Use a | b) |
paragraph | unchanged |
Valid table with :--- and ---: alignment |
table | unchanged, alignment kept |
Nine inputs are not proof that it handles everything. The function only touches lines that start and end with a pipe, so tables written without outer pipes are left as they are. Test it on real output from your own prompts.
Prevent it in the prompt
Repair is a safety net. You will get fewer broken tables if the prompt is clear about the format, for example: "Return tables as GitHub Flavored Markdown with a header row, a delimiter row and one line per row. Do not put tables in code blocks. Escape pipes inside cells as |." Keep the repair step anyway, because models do not always follow format rules.
Repair first, then sanitize
Fixing a table changes the layout, not the safety. A model can still put a javascript: link or a tracking image inside a cell. After repair, convert to HTML and run a sanitizer with an allow-list, as shown in how to render LLM Markdown output safely. If you render in React, see is react-markdown safe for ChatGPT and Claude output?. For the full table syntax, read the GitHub Flavored Markdown guide.
Frequently asked questions
Why does my Markdown table show up as plain text?
Usually the delimiter row is missing or has a different number of cells from the header row. The GFM spec says the table is then not recognized. Also check that your renderer has GFM turned on.
How do I put a pipe character inside a table cell?
Escape it with a backslash: \|. The GFM spec says this also works inside inline spans such as code, so `a \| b` renders as code containing a pipe.
Does every row need the same number of cells?
No. Only the header and delimiter rows must match. If a body row has fewer cells, the spec says empty cells are inserted. If it has more, the extra cells are dropped, which can silently lose data.
Can I build a clean table from spreadsheet data instead?
Yes. Paste CSV or spreadsheet cells into the free Markdown table generator. It runs in your browser and outputs a valid GFM table.
Does the TexToolsAI API repair broken tables?
No. The API parses GFM with marked and sanitizes the HTML, so a valid table comes back as a table. Run a repair step like the one above first. You can test the result in the playground, see the request format in the docs, and check the pricing for API keys.