# Parse a Messy CSV or JSON File With Edge Cases

> How to read a messy CSV or JSON file without losing rows or trusting bad values, explained simply for your AI interview.

**In short:** Use a real parser such as Python's csv module, not a plain split on commas. Check every row, and keep bad rows in a review pile with their line numbers, instead of crashing or dropping them.

AI and LLM interview question Q399, Forward Deployed Engineering and applied AI. Beginner, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/parse-a-messy-csv-json-file-with-edge-cases

## Say it in 30 seconds

I would read the file with a real parser, not split it on commas, because quoted cells can hold commas and line breaks. First I remove the hidden byte order mark and read the file as UTF-8. Then I check every row for the right number of fields, a price that is a real number (not N/A, nan or inf), and any required values. Good rows go on. Bad rows go into a review pile with their line number and reason. Last, I count rows in and rows out, so nothing disappears quietly.

## Say it in 2 minutes

Messy files break in predictable ways. A quoted cell can hold a comma or a line break. Some rows are short, some are blank, and a price can read 1,200.50 or N/A. Some Windows tools add a hidden marker, the BOM, to the start of a UTF-8 file. A plain split on commas breaks on the first quoted comma, so I use a real parser for CSV and the json module for JSON.

Next I check every row. Does it have the right number of fields? Is the price a real number once the thousands separator is removed? Is a required value there? Rows that pass go on. Rows that fail are not thrown away. They go into a review pile with the line number and the reason, so a person can fix the supplier's file.

JSON has its own traps. A repeated key quietly keeps only the last value. Python's JSON reader accepts NaN, which the JSON standard does not allow, so I check numbers before I trust them. I also cap the size of anything that comes from outside, because a hostile file can use a lot of memory.

Last, I count. Rows in should equal clean rows plus flagged rows. If the numbers do not match, something was lost, and I fix that before anyone loads the data. The worst outcome is an import that looks clean and quietly lost thirteen rows.

## What is a messy CSV or JSON file, in plain words?

A CSV file is plain text. Usually each line is a row, and a separator, usually a comma, splits the values. Spreadsheets export this format, and it looks simple until a real file arrives. A JSON file nests data inside curly braces and square brackets. Most apps and web services send JSON.

Picture a clerk who receives a delivery note from a supplier. One line has an extra column, one is blank, and one price says N/A. A careful clerk does not guess the missing numbers. They sort each line into fine or ask the supplier, and write down the reason. A parser does the same job for a file.

The stakes are real. A procurement team might send a supplier price list every week, and an AI tool drafts purchase orders from it. One lost row can mean one product missing from an order.

- **Delimiter:** The character that separates values. Usually a comma, sometimes a semicolon or a tab.
- **BOM:** Byte order mark: an invisible signature some tools put at the start of a UTF-8 file.
- **Quoted field:** A value wrapped in double quotes, so a comma or line break inside it does not split it.
- **Flag:** A note on a row we cannot trust, kept with its line number and the reason.

## Which edge cases break a simple parser?

Most breakage comes from a few predictable cases. The Python docs explain why it happens: there is no strict CSV standard, so tools produce subtly different CSV data.

> "Due to the lack of a strict CSV specification, different applications produce subtly different CSV data." (Python documentation)

- **A comma inside quotes:** A quoted cell can hold a comma. A plain split cuts that row in two.
- **A line break inside a cell:** One record can span two physical lines, so counting lines does not count records.
- **A hidden marker at the start:** The BOM sits before the first column name and can stick to it, so the header no longer matches.
- **Numbers written for people:** A price such as 1,200.50 has a thousands separator. Other countries write 1.200,50, so agree the format before you parse.
- **Short, long and blank rows:** Some rows lack a value or have an extra one. Blank lines appear between blocks of data. The csv reader skips a blank line without a flag, because a blank line is not a record. Look at line 3 of the sample file.
- **Formulas in cells:** A cell such as =9.99*2 is only text to a parser, but a spreadsheet may run it. Treat it as a bad price.

> **Tip:** Auto-detecting the separator is an estimate from a sample. Python's own detector, called a sniffer, works this way, so set the delimiter yourself when you know it.

## How do you parse without losing a row?

Read the file as UTF-8, remove the BOM, let the csv module handle quotes and line breaks, then check every row. Rows that fail are kept, never dropped. DictReader fills the missing values of a short row with None and puts extra values under a key of None, so both cases show up in the checks.

*Diagram, From a messy file to clean rows and a review pile: A messy file goes in. Good rows go on to the next step. Bad rows wait in a review pile with their line number and reason, so nothing disappears without a trace.*
1. The raw bytes go in, and the hidden BOM marker is removed first.
2. The csv module reads quotes and line breaks correctly.
3. Each row is handed over as named values, with a line number.
4. Rows that pass every check go on to the next step.
5. Rows that fail are kept with their line and reason, never dropped.

1. **Ask three questions first:** Which encoding and separator? Can a value span lines? What should a bad row do? Agree the answers with the people who send the file.
2. **Use a real parser:** The csv module reads quotes and line breaks. A plain split on commas does not.
3. **Check each row:** The right number of fields, a real number in the price (Python's float() also accepts the words nan and inf, so reject those too), and every required value filled in.
4. **Flag, never drop:** A bad row goes to the review pile with its line number and reason.
5. **Count the rows:** Rows in should equal clean rows plus flagged rows. If not, something was lost.

Real files fail in small ways, so the code below runs a made-up supplier file with most of the common cases at once. The marked lines do the work.

```python
import csv, io

RAW = """\ufeffSKU,Item,Unit price,Qty,Note
A-100,"Cable, 2 m","1,200.50",4,

A-101,Adapter,9.99,,"Gift box
see PO"
A-102,Dock,=9.99*2,2,ok
A-103,Hub,N/A,3,,extra"""

def parse(text):
    reader = csv.DictReader(io.StringIO(text.removeprefix("\ufeff"), newline=""))
    good, flags = [], []
    for rec in reader:
        where = f"line {reader.line_num}"
        if None in rec or None in rec.values():
            flags.append(f"{where}: wrong number of fields")
            continue
        try:
            rec["Unit price"] = float(rec["Unit price"].replace(",", ""))
        except ValueError:
            flags.append(f"{where}: price {rec['Unit price']!r} is not a number")
            continue
        if not rec["Qty"].isdigit():
            flags.append(f"{where}: qty missing")
            continue
        good.append(rec)
    return good, flags
good, flags = parse(RAW)
print(*good, *flags, sep="\n")
```

Output:

```text
{'SKU': 'A-100', 'Item': 'Cable, 2 m', 'Unit price': 1200.5, 'Qty': '4', 'Note': ''}
line 5: qty missing
line 6: price '=9.99*2' is not a number
line 7: wrong number of fields
```

Three things to notice. The price becomes a number only after we convert it, because csv gives back text for every value. A record that spans lines is reported at the line where it ends, so the quantity flag points at line 5. The missing quantity is flagged and held back, because a person should decide what it means. The demo has no short row, but the same check catches one.

## What do JSON files add?

JSON is stricter about structure, but it has traps of its own. The Python docs say JSON is specified by RFC 7159 and by ECMA-404, and Python's json module follows it with a few known gaps. Four matter most in practice.

- **A marker at the start breaks it:** This module's deserializer raises a ValueError when an initial BOM is present. Strip the marker first.
- **A repeated key keeps the last value:** The parser ignores all but the last name-value pair for a given name, with no error. A duplicate price can quietly replace the first one.
- **NaN and Infinity are accepted:** Python takes these values, although the JSON rules do not allow them. Check numbers before you trust them.
- **Huge inputs use memory:** A hostile file can use a lot of CPU and memory, so cap the size of anything that comes from outside.

For a very large file, Python's json tool can parse one JSON object per input line with its --json-lines option, so you can check one record at a time.

> **Tip:** Asked about JSON in an interview? Name the traps, then say you check each record against the shape you expect before it is loaded.

## Why check the file you write back out?

Parsing a formula cell is safe, because the parser only reads text. The danger comes when you write the cleaned file back out for someone to open in a spreadsheet. OWASP calls this CSV injection, or formula injection.

> "Keep in mind that it is not sufficient to make sure that the untrusted user input does not start with these characters." (OWASP)

So the fix belongs on the export side. Neutralise risky cells before the file is written for a spreadsheet, and treat that output as its own job. OWASP also warns that no single method suits every spreadsheet app and every downstream reader, so say so when you explain it.

### How would you handle a supplier file that changes shape every month?

Columns move, headers get renamed, and a new column can appear without warning. I would map columns by header name rather than by position, keep a saved layout for each supplier, and stop the load when a required header is missing.

- **Without a plan: Shifted columns.** The load runs, and a quantity lands in the price column.
- **With a plan: The load stops early.** The file is held, the supplier gets the list of missing headers, and last month's prices stay live.

Before you ship, write one test per supplier with a sample of their real file. A small test catches the change that would otherwise break production.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Questions first: encoding, separator, and what a bad row should do.
- [ ] A real parser (csv and json), never a plain split on commas.
- [ ] The BOM, quoted commas and line breaks handled.
- [ ] Bad rows flagged with line numbers, never dropped silently.
- [ ] Counts reconciled: rows in equal clean rows plus flagged rows.
- [ ] Output checked: a formula cell can run when a spreadsheet opens it.

**Common traps**

- Trap: "Just split on commas and fix the errors later." Better: A quoted comma breaks a split without any error. Use a real parser so the rows are right first time.
- Trap: "Skip the bad rows and move on." Better: Skipped rows vanish from the totals. Keep them in a review pile with a reason.
- Trap: "The model can clean up the file." Better: A model can invent a missing value. Use code for the checks and a person for the judgement calls.

## Can you spot the bug?

**Spot the bug:** A colleague wrote this loader. Which line can silently mangle the data?

A. reader = csv.DictReader(open(path, newline='', encoding='utf-8-sig'))
B. rows = [line.split(',') for line in open(path).read().splitlines()]
C. data = json.loads(text.removeprefix('\ufeff'))
D. print(len(reader.fieldnames))

**Answer:** B. Splitting every line on commas breaks a quoted item name that contains a comma, so the values shift into the wrong columns with no error. Use csv, which reads the quotes.

**Quick check:** A supplier file has 4,000 rows, and 13 are short or have extra values. Your team agreed that one bad row must not block the other rows. What is the right outcome?

A. Drop the 13 rows and report nothing
B. Stop the whole import at the first bad row
C. Load the 3,987 clean rows and keep the 13 in a review pile with line numbers
D. Ask a model to fill the missing fields in the 13 rows

**Answer:** C. Clean rows should go on, and bad rows should wait with their line and reason. Dropping them hides the loss, stopping wastes 3,987 good rows, and a model would invent values nobody checked.

## Can you answer these from memory?

**Flash cards**

- **Why not split on commas?** A quoted cell can hold a comma or a line break. Use the csv module.
- **What is a BOM?** An invisible signature at the start of a file. Strip it before parsing.
- **Do you drop a bad row?** No. Keep it in a review pile with its line number and reason.
- **What does JSON do with a repeated key?** It keeps only the last value and raises no error.
- **What is a count check?** Rows in equal clean rows plus flagged rows. If not, something was lost.
- **Is a formula cell safe to parse?** Yes, as text. The risk comes when the cleaned file opens in a spreadsheet.

## Likely follow-up questions

- Q398 Take-home: messy data → records, with low-confidence flags. https://designervenkat.online/interview/ai/take-home-messy-data-records-with-low-confidence-flags
- Q387 How do you deal with messy customer data? https://designervenkat.online/interview/ai/how-do-you-deal-with-messy-customer-data
- Q478 Parse and validate LLM JSON, retrying on failure. https://designervenkat.online/interview/ai/parse-and-validate-llm-json-retrying-on-failure
- Q085 How do you get reliable JSON output? https://designervenkat.online/interview/ai/how-to-get-reliable-json-from-an-llm
- Q448 How do you extract structured data from documents and images? https://designervenkat.online/interview/ai/extract-structured-data-from-documents-and-images
- Q400 Build a small CLI tool. https://designervenkat.online/interview/ai/build-a-small-cli-tool

## Learn it in depth

- [CSV files, up close](https://designervenkat.online/learn/machine-learning/csv-files)
- [JSON files](https://designervenkat.online/learn/machine-learning/json-files)
- [Data cleaning: fixing a messy table](https://designervenkat.online/learn/machine-learning/data-cleaning)
