Skip to main content
Guide 7 min read

How to Convert CSV to JSON (and Back) Without Breaking Quotes or Delimiters

You need to convert CSV to JSON, so you export a spreadsheet and run it through a converter. Half the rows look wrong. A name like Smith, John splits into two fields. A stray quote ends a string early. The ZIP code 02134 turns into 2134. It sounds like a one click job, and it breaks because CSV looks simple when it isn’t.

This guide explains why conversions break and how to prevent it, in both directions. You’ll learn the quote and comma rules, how to spot the wrong delimiter, what encoding does to your first column and how to keep numbers from changing. You’ll also get a safe method and a quick test to prove nothing got lost.

Why CSV breaks so easily

CSV is plain text with a loose agreement behind it. A document called RFC 4180 describes the common shape, but plenty of tools ignore parts of it. Every value is text, and any value can hold a comma, a quote or even a line break.

JSON is the opposite. It’s strict. One unescaped quote makes the whole file invalid, and that’s why a small CSV quirk can turn into a big JSON headache.

The quote and comma rules

The rules are short. A value that contains a comma, a double quote or a line break gets wrapped in double quotes. A double quote inside a quoted value is written twice. That’s the whole trick, and it explains most surprises. Look at this row:

name,note
"Smith, John","He said ""hello"""

A correct converter reads the quotes, drops the wrapping ones, turns each doubled quote into one and escapes it for JSON:

[
  {
    "name": "Smith, John",
    "note": "He said \"hello\""
  }
]

Now the warning. Never split a CSV line on commas by hand, and never use a quick find and replace. Both ignore the quotes, so Smith, John becomes two columns. Use a real parser.

Delimiters: not every CSV uses commas

The C stands for comma, but plenty of files use something else. Semicolons are common in countries where the comma marks decimals, and Excel follows your regional settings when it saves a CSV. Tabs, pipes and other characters show up too.

Open the file in a plain text editor and read the first line. If you see one long cell in a spreadsheet, or JSON where every row has a single giant key, the delimiter is wrong. Tell the converter which character to use instead of letting it guess.

Decimal commas deserve a warning. A value like 3,14 inside a comma separated file only survives if it sits in quotes. If it doesn’t, the number splits in two.

Encoding and the invisible first character

Garbled letters, like é where you expect é, mean the file isn’t UTF 8 or was read as the wrong encoding. Save the CSV as UTF 8 and read it as UTF 8.

There’s a sneakier problem. Excel’s CSV UTF 8 option adds a hidden marker at the start of the file, called a byte order mark. Some parsers keep it as part of the first header. Your first key then looks like name but isn’t, and every lookup for name returns nothing. If a key looks right and still fails, suspect the marker. Strip it, or use a reader that handles it.

Types: CSV has none, JSON has several

Everything in CSV is text. JSON has strings, numbers, true and false, and null. A converter has to guess, and guesses cause damage:

  • Leading zeros vanish. ZIP codes and product codes must stay strings.
  • Long IDs lose digits. Many tools read numbers beyond 15 digits as floating point values, and the last digits change.
  • Empty cells become an empty string in one tool and null in another. Pick one rule and keep it.
  • The words true and false may turn into real booleans, which is great or awful depending on your data.
  • Dates stay text, so use one format everywhere. ISO 8601 is the safest. Our timestamp converter helps you standardize them.

Decide the type of each column before you convert. IDs and codes are strings, even when they look like numbers.

How to convert CSV to JSON step by step

  1. Open the file in a text editor and check the delimiter, the quotes and the header row.
  2. Clean the headers. Make each one unique and non empty, because duplicate headers overwrite each other in JSON.
  3. Convert with a real parser. Our CSV to JSON converter handles quoted fields and lets you set the delimiter.
  4. Check the types, especially IDs, ZIP codes and empty cells.
  5. Paste the result into our JSON formatter. If the JSON is invalid, it tells you where.
  6. Spot check the rows that held commas, quotes and line breaks.

Prefer code? Python’s built in csv module does the parsing for you:

import csv, json

with open("data.csv", newline="", encoding="utf_8_sig") as f:
    rows = list(csv.DictReader(f))

with open("data.json", "w", encoding="utf8") as f:
    json.dump(rows, f, indent=2, ensure_ascii=False)

The utf_8_sig setting strips the hidden marker, and every value stays a string, which protects your leading zeros. Sending the JSON to an API next? Our guide on REST API requests covers what comes after.

Going back: JSON to CSV

A flat array of objects converts cleanly. Real JSON is rarely that tidy, so plan for three problems:

  • Nested objects. Flatten them into columns with dotted names, like address.city.
  • Arrays. Join the items into one cell with a separator you won’t find in the data, or write one row per item.
  • Uneven objects. When records have different keys, build the header from the union of all keys and leave missing values blank.

Then let the writer handle quoting. A proper CSV writer wraps values that contain commas, quotes or line breaks and doubles the quotes for you:

import csv, json

rows = json.load(open("data.json", encoding="utf8"))

with open("out.csv", "w", newline="", encoding="utf8") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

That sample assumes every record shares the same keys, so build the field list yourself when they don’t. One security note too. Excel can run a cell as a formula when its value starts with an equals sign, a plus sign, a minus sign or an at sign. If your data comes from users, prefix those cells with a single quote before you export. Starting from XML instead? Our XML to JSON converter covers that path.

Mistakes that break conversions

These slips cause most of the damage:

  • Splitting lines on commas by hand.
  • Guessing the delimiter instead of checking it.
  • Ignoring the hidden marker at the start of the file.
  • Letting a tool turn every value that looks like a number into a number.
  • Leaving duplicate or blank headers in the first row.
  • Keeping empty lines and trailing commas, which create junk rows.
  • Opening the CSV in a spreadsheet and saving it again. Excel can rewrite values, turn codes into dates and drop leading zeros.

Stray characters hide in big files. A pattern in our regex tester can find lines with an odd number of quotes before you convert.

Prove nothing got lost

Run a round trip. Convert your CSV to JSON, convert it back and compare the two CSV files in our text diff checker. Small differences in quoting or line endings are fine. A changed value is not.

Also compare the row counts, and open a few rows by hand, especially the ones with commas, quotes or line breaks inside. If those survive, the rest will too.

A checklist before you convert

Run through this list once:

  1. Open the file in a text editor and confirm the delimiter.
  2. Confirm the encoding is UTF 8, and strip any hidden marker.
  3. Make every header unique and non empty.
  4. Decide which columns stay strings, such as IDs and ZIP codes.
  5. Pick one rule for empty cells.
  6. Use a real parser, never a split on commas.
  7. Validate the JSON in a formatter.
  8. Run a round trip and compare the results.

The short version

Quotes wrap values that hold commas, quotes or line breaks, and a quote inside a quoted value is doubled. Check the delimiter, read the file as UTF 8, keep IDs as strings and use a real parser in both directions. Validate the JSON and run a round trip to catch any change.

Pick a CSV that gave you trouble before and run it through the steps above. You’ll see the problem in minutes.

Free browser based tools on Black Claaw to convert data, validate JSON, hunt stray characters and compare results.

View all tools

Advertisement