DEV Community

Yogeshwaran Tech Tools
Yogeshwaran Tech Tools

Posted on

Read, clean and convert CSV and JSON in Python (no libraries needed)

You do not need pandas for everyday CSV and JSON jobs. Python's standard library handles most of them in a few lines. These are the recipes I reuse.

1. Read a CSV into dictionaries

import csv

with open("people.csv", newline="", encoding="utf-8-sig") as f:
    rows = list(csv.DictReader(f))

print(rows[0])   # {'id': '1', 'email': 'a@x.com'}
Enter fullscreen mode Exit fullscreen mode
  • newline="" lets the csv module handle line endings correctly.
  • utf-8-sig removes the invisible BOM that Excel adds, so your first column is not named id.
  • All values are strings. Convert with int() or float() where needed.

2. Remove duplicate rows (by a column)

seen, unique = set(), []
for row in rows:
    key = row["email"].strip().lower()
    if key in seen:
        continue
    seen.add(key)
    unique.append(row)
print(len(rows), "->", len(unique))
Enter fullscreen mode Exit fullscreen mode

Normalising the key (strip().lower()) catches A@x.com and a@x.com as the same person.

3. Write rows back to CSV

with open("clean.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(unique)
Enter fullscreen mode Exit fullscreen mode

4. CSV to JSON

import json

with open("clean.json", "w", encoding="utf-8") as f:
    json.dump(unique, f, indent=2, ensure_ascii=False)
Enter fullscreen mode Exit fullscreen mode

ensure_ascii=False keeps non-English text (such as Tamil) readable instead of escaping it as க.

5. JSON to CSV (flat objects)

import csv, json

data = json.load(open("data.json", encoding="utf-8"))
if isinstance(data, dict):
    data = [data]
columns = list(dict.fromkeys(k for row in data for k in row))

with open("data.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=columns)
    w.writeheader()
    for row in data:
        w.writerow({k: json.dumps(v) if isinstance(v, (dict, list)) else v for k, v in row.items()})
Enter fullscreen mode Exit fullscreen mode

The dict.fromkeys trick collects every column in first-seen order, even when objects have different keys. Nested lists or dicts are stored as JSON text in the cell.

6. Handle bad data safely

def to_int(value, default=0):
    try:
        return int(str(value).strip())
    except ValueError:
        return default
Enter fullscreen mode Exit fullscreen mode

Wrap conversions so one bad row does not crash the whole job, and log what you skipped.

Common mistakes

  1. Opening the file without newline="", which creates blank lines on Windows.
  2. Forgetting the encoding, which breaks on non-English text.
  3. Comparing strings that differ only in case or spaces.
  4. Loading a huge file with list(...). For big files, loop over the reader and write as you go.
  5. Overwriting your only copy. Write to a new file first.

Ready-made versions

I packaged the CSV dedupe and JSON to CSV scripts (with usage help) in a free scripts repo: https://gitlab.com/yogeshwaran-tech-tools/python-automation-scripts and a larger set of ten here: https://yogeshwarantechtools.myinstamojo.com/product/python-automation-scripts-pack-10-ready-to-r

Written by Yogeshwaran Tech Tools. Corrections welcome.

Top comments (0)