To convert CSV to JSON without losing data, parse the file with a real CSV parser rather than splitting on commas, decode it with the correct encoding, and decide deliberately how to type each column. The three places data goes missing are quoted fields, text that looks like a number, and empty cells.
How CSV and JSON differ
CSV is a flat table. Every row has the same columns, and every value is plain text. JSON is a tree: values can be strings, numbers, booleans, null, arrays or nested objects. Converting CSV to JSON is therefore mostly a matter of choosing types, since the structure is simple. Going the other way, from JSON to CSV, is harder because nested data has to be flattened.
The usual mapping turns the header row into object keys and each following row into one object, producing an array of objects. A file with columns id,name,zip becomes a list where each item has those three keys. If you are also weighing JSON against other text formats, the post on JSON vs YAML covers the trade-offs.
The CSV rules that break naive parsers
Most CSV files follow the conventions written down in RFC 4180, though many real-world files bend them. The rules that matter most are these:
- Fields are separated by commas and rows by line breaks.
- A field containing a comma, a double quote or a line break must be wrapped in double quotes.
- A double quote inside a quoted field is written as two double quotes.
- A quoted field may span several lines, so one record is not always one line of the file.
This is why line.split(",") fails. It cuts "Smith, Jane" in two and shifts every later column. Splitting by lines also breaks any record with a line break inside a quoted note. Use a parser that implements the quoting state machine.
Worked example
Take this file, where the first record has a comma in the name and quotes in the note, and the second has two empty-ish cells:
id,name,note,zip,amount
1,"Smith, Jane","Said ""hello""",02134,12.50
2,Lee,,90210,
Parsed with Python's csv module, with the amount converted to a number and the empty amount set to null, it produces this JSON:
[
{
"id": "1",
"name": "Smith, Jane",
"note": "Said \"hello\"",
"zip": "02134",
"amount": 12.5
},
{
"id": "2",
"name": "Lee",
"note": "",
"zip": "90210",
"amount": null
}
]
Notice three decisions. The name keeps its comma, the doubled quotes became one escaped quote, and the ZIP code stayed a string so the leading zero survived. Notice also that 12.50 became 12.5, which is the same number but no longer shows trailing zeros. If trailing zeros matter, such as in a version number or a fixed-format price, keep that column as a string.
Type problems
CSV has no types, so a converter must guess or be told. Guessing is where damage happens.
Leading zeros
ZIP codes, phone numbers, account numbers and product codes are identifiers, not quantities. Coercing 02134 to a number gives 2134, and the zero cannot be recovered. A useful rule: if you would never add or average the column, keep it as a string.
Large integers
JavaScript represents numbers as 64-bit floating point, so integers are exact only up to 253 minus 1, which is 9007199254740991. Beyond that, values get rounded. In Node.js, 9007199254740993 prints as 9007199254740992. Database IDs, social-media post IDs and card-like numbers can exceed this limit, so store them as strings in the JSON.
Dates
JSON has no date type. Keep dates as strings, and prefer ISO 8601 (2026-12-03 or 2026-12-03T14:30:00Z) because it sorts correctly and is unambiguous. A value like 03/04/2026 means different days in different countries, so do not convert it unless you know the source locale.
Delimiters, encoding and the BOM
Despite the name, not every CSV uses commas. In many European locales, where the comma is the decimal separator, spreadsheet software exports with a semicolon. Tab-separated files are also common. If your JSON comes out with one giant key containing the whole header, the delimiter is wrong. Detect it by looking at the first line, or let the user choose.
Encoding is the other frequent trap. Excel's "CSV UTF-8" export adds a byte order mark (BOM), three bytes at the start of the file. If you read it as plain UTF-8, the first header becomes \ufeffid, and a lookup for id fails. In Python, open the file with encoding="utf-8-sig", which strips the BOM. In JavaScript, remove a leading \uFEFF character. Files saved in older Windows encodings will show garbled accents when read as UTF-8, so confirm the encoding with the source.
Empty values
An empty CSV cell can mean an empty string, a missing value or zero information. JSON distinguishes "" from null, so you must choose. A common convention: use null for empty numeric, date and boolean columns, where an empty string would break validation, and keep an empty string for text columns. Whatever you choose, apply it consistently and document it for whoever consumes the JSON.
Going from JSON back to CSV
Nested objects have no natural place in a flat row. Two common approaches are flattening keys with dots, so {"user":{"city":"Oslo"}} becomes a column named user.city, and joining short arrays into one cell with a separator. Arrays of objects are harder, because they imply multiple rows per record or multiple extra columns. Decide on one rule up front, and note that unflattening later requires the same convention.
Code in Python and JavaScript
Python, using only the standard library:
import csv, json
with open("data.csv", newline="", encoding="utf-8-sig") as f:
rows = list(csv.DictReader(f)) # use delimiter=";" if needed
# convert only the columns that are truly numeric
for r in rows:
r["amount"] = float(r["amount"]) if r["amount"] else None
print(json.dumps(rows, ensure_ascii=False, indent=2))
JavaScript, with a small parser that handles quotes, doubled quotes and line breaks inside fields:
function parse(t, d = ",") {
const rows = []; let r = [], f = "", q = false;
for (let i = 0; i < t.length; i++) {
const c = t[i];
if (q) {
if (c === '"') { if (t[i+1] === '"') { f += '"'; i++; } else q = false; }
else f += c;
} else if (c === '"') q = true;
else if (c === d) { r.push(f); f = ""; }
else if (c === "\n" || c === "\r") {
if (c === "\r" && t[i+1] === "\n") i++;
r.push(f); rows.push(r); r = []; f = "";
} else f += c;
}
if (f !== "" || r.length) { r.push(f); rows.push(r); }
return rows;
}
const [h, ...b] = parse(text.replace(/^\uFEFF/, ""));
const out = b.map(x => Object.fromEntries(h.map((k, i) => [k, x[i]])));
For quick one-off jobs, the CSV to JSON converter does the same work in the browser, with a choice of delimiter.
Common mistakes
- Splitting on commas. It breaks on quoted commas and multi-line fields.
- Auto-converting every numeric-looking value. This strips leading zeros and rounds large IDs.
- Ignoring the BOM. The first key silently changes, and later code cannot find it.
- Assuming a comma delimiter. A semicolon or tab file will parse as a single column.
- Mixing null and empty string. Downstream code then needs to handle both.
Frequently Asked Questions
Why are all my JSON values strings?
Because CSV stores only text. Safe parsers keep strings unless you convert specific columns. That is usually the right default, since it loses nothing.
How do I keep leading zeros?
Treat identifier columns as strings and never run a number conversion on them. Also check that the spreadsheet application did not already remove the zeros before export.
What should I do with a very large ID?
Keep it as a string in the JSON. If a consumer needs a number, use a language or library with arbitrary-precision integers, such as BigInt in JavaScript.
Can I convert nested JSON to CSV without losing structure?
Only with a flattening convention such as dotted column names. Without one, nesting is lost, so keep the JSON as the source of truth.
Comments
Leave a Comment
No comments yet. Be the first to comment!