How Token Efficiency Compares Across Markdown Tables, JSON Arrays, and YAML for CSV Data
For pure token efficiency on flat tabular CSV data, raw CSV is typically the most compact because column headers appear only once and rows use minimal delimiters (commas + newlines). Among the three options you asked about—Markdown tables, YAML, and JSON arrays—Markdown tables are generally the most token-efficient (often using roughly half or fewer tokens than JSON arrays or YAML on wide/tall flat tables), followed by YAML or compact JSON, with pretty-printed JSON using the most tokens due to repeated key names, braces, quotes, and indentation.
- Why JSON arrays cost the most tokens: Every object repeats all property keys (
"order_id":,"status":,"amount":) plus quotes, colons, commas, and brackets—and pretty-printing adds newlines and spaces on top. Only minified/compact JSON (JSON.stringify(rows)) reduces structural overhead, though keys still repeat on every row. - Why YAML sits in the middle: YAML drops quotes and braces and uses indentation instead, beating pretty JSON on token count, but it still repeats field keys on every record and adds indentation/dash tokens.
- Why Markdown tables are usually more token-efficient than JSON/YAML (and where they trade off): A Markdown table declares column names once in the header row and adds one separator row (
| --- | --- |), using pipe (|) delimiters instead of repeating keys on every row. However, pipes (|) and spaces around cells still cost more tokens than raw CSV, and long wide tables with many columns can occasionally cause column-alignment mistakes in models if not kept clean.
Steps to Choose and Convert Tabular CSV Data for Token Efficiency
- Keep flat CSV directly when maximum token savings is the priority: If your source data is already flat tabular CSV with clean values and no complex nesting, passing the CSV directly (or trimming unused columns/rows first) usually gives the lowest token count.
- Convert CSV to a Markdown table when you want better readability/structure than JSON/YAML with lower token usage: Use a Markdown table when passing a small-to-medium table alongside prose instructions and you want fewer tokens than JSON arrays or YAML.
- Avoid pretty-printed JSON arrays for large row counts: Never pretty-print large tabular arrays in prompts; if you must use JSON (for example, when rows contain nested arrays/objects or must match a schema), strip whitespace (
JSON.stringify) and project only needed columns. - Measure with your actual model’s tokenizer before locking in: Token counts vary by BPE/tiktoken vocabulary, numeric formatting, and column cardinality—benchmark candidate formats on a real sample of your CSV rows and evaluate answer accuracy on lookup/aggregation tasks, not just raw token count.
TypeScript Example: CSV to Markdown Table Converter and Token-Size Comparison Helper
export interface TabularComparison {
rawCsv: string;
markdownTable: string;
compactJson: string;
prettyJson: string;
yamlList: string;
}
function parseSimpleCsv(csv: string): { headers: string[]; rows: string[][] } {
const lines = csv
.trim()
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
if (lines.length === 0) {
return { headers: [], rows: [] };
}
const splitRow = (line: string): string[] => {
const cells: string[] = [];
let current = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (ch === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i++;
} else {
inQuotes = !inQuotes;
}
} else if (ch === "," && !inQuotes) {
cells.push(current.trim());
current = "";
} else {
current += ch;
}
}
cells.push(current.trim());
return cells;
};
const headers = splitRow(lines[0]);
const rows = lines.slice(1).map(splitRow);
return { headers, rows };
}
export function csvToMarkdownTable(csv: string): string {
const { headers, rows } = parseSimpleCsv(csv);
if (headers.length === 0) return "";
const escapePipe = (v: string) => v.replace(/\|/g, "\\|");
const headerLine = `| ${headers.map(escapePipe).join(" \vert{} ")} \vert{}`; const separatorLine = `\vert{} ${headers.map(() => "---").join(" | ")} |`;
const bodyLines = rows.map(
(row) => `| ${headers.map((_, idx) => escapePipe(row[idx] ?? "")).join(" \vert{} ")} \vert{}` ); return [headerLine, separatorLine, ...bodyLines].join("\n"); } export function csvToYamlList(csv: string): string { const { headers, rows } = parseSimpleCsv(csv); if (headers.length === 0) return ""; const out: string[] = []; for (const row of rows) { headers.forEach((h, idx) => { const val = row[idx] ?? ""; const prefix = idx === 0 ? "- " : " "; out.push(`${prefix}${h}:${JSON.stringify(val)}`);
});
}
return out.join("\n");
}
export function buildTabularFormats(csv: string): TabularComparison {
const { headers, rows } = parseSimpleCsv(csv);
const objects = rows.map((row) => {
const obj: Record<string, string> = {};
headers.forEach((h, idx) => {
obj[h] = row[idx] ?? "";
});
return obj;
});
return {
rawCsv: csv.trim(),
markdownTable: csvToMarkdownTable(csv),
compactJson: JSON.stringify(objects),
prettyJson: JSON.stringify(objects, null, 2),
yamlList: csvToYamlList(csv),
};
}
Helpful Tips for Tabular Data in LLM Prompts
- Filter columns and pre-aggregate in code before sending to the LLM: Dropping unused columns, rounding noisy floats, or filtering irrelevant rows in Node.js/TypeScript before serialization saves far more tokens—and improves accuracy—than switching serialization formats alone.
- Watch out for cell values containing commas, quotes, or pipes: If CSV fields contain commas or quotes, use a proper RFC-4180 CSV parser (like
csv-parse) rather than naive.split(","), and escape|inside Markdown table cells so columns do not shift. - Do not optimize purely for lowest token count on high-precision lookups: On dense or wide tables, test whether a Markdown table or CSV causes row/column misalignments compared to a slightly more verbose format for your specific task.
You must log in or register to comment.
