Sometimes you export a spreadsheet and the next tool in your pipeline wants JSON instead. Pulling in pandas for that feels like overkill — Python's standard library already has everything needed. Here's a small converter that does it in a handful of lines, no third-party packages required.
1. Reading the CSV
csv.DictReader turns each row into a dictionary keyed by the header row automatically — no manual header parsing needed.
import csv
def read_csv(csv_path):
with open(csv_path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
return list(reader)
Wrapping the result in list() consumes the whole reader up front, which is fine for small-to-medium files and much simpler to reason about than lazily iterating later.
2. Writing the JSON
import json
def write_json(rows, json_path):
with open(json_path, "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2)
indent=2 keeps the output human-readable, which matters if anyone will actually open the file to sanity-check it.
3. Wiring it together
def csv_to_json(csv_path, json_path):
rows = read_csv(csv_path)
write_json(rows, json_path)
return len(rows)
Returning the row count gives a quick sanity check — if you expected 500 contacts and it says 3, something upstream went wrong before you even open the output file.
4. The full script, start to end
import csv
import json
def read_csv(csv_path):
with open(csv_path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
return list(reader)
def write_json(rows, json_path):
with open(json_path, "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2)
def csv_to_json(csv_path, json_path):
rows = read_csv(csv_path)
write_json(rows, json_path)
return len(rows)
if __name__ == "__main__":
count = csv_to_json("contacts.csv", "contacts.json")
print(f"Converted {count} rows -> contacts.json")
5. Trying it out
Given a contacts.csv like:
name,email,city
Alice,alice@example.com,Austin
Bob,bob@example.com,Denver
Running the script produces:
[
{
"name": "Alice",
"email": "alice@example.com",
"city": "Austin"
},
{
"name": "Bob",
"email": "bob@example.com",
"city": "Denver"
}
]
Wrap-up
This covers the common case: clean, well-formed CSVs with a single header row. For messier real-world files — inconsistent encodings, embedded commas, multi-line fields — Python's csv module already handles most of that correctly via proper quoting, but very irregular exports may need extra cleanup before conversion. Still, for a quick spreadsheet-to-API pipeline, this is often all you need.
Top comments (0)