CSV to JSON converter in 10 lines of code

Devashish Patil
CodeByte
Published in
2 min readMar 10, 2022

--

If you do a lot of scripting with python, many a times you might need to convert CSVs to JSON files for multitude of reasons. I’ll show you a step-by-step approach on how you can do that in just 10 lines of Python code.

Let’s say you have a CSV file like this:

Let’s dive right into the code. First of all, do the imports, json is all we need.

import json

Next, let’s read our CSV file like this:

with open('path/to/csv/file', 'r') as f:
lines = f.readlines()

We’ll assume the first row to be the column headers and reserve them as the keys for the JSON file.

keys = lines[0].strip().split(',')

Let’s now create an empty list to put the output content.

output = []

Now, we’ll convert each row as a dictionary containing first_name, last_name and age as keys. Notice, that we are using the zip function to map these keys with the elements in the rows.

for line in lines[1:]:
values = line.strip().split(',')
output.append(dict(zip(keys, values)))

The last step is to save this data in a JSON file. Here’s how we do that:

with open('path/to/json/file', 'w') as f:
json.dump(output, f, indent=4)

Your output JSON file will look like this:

I hope you found this useful. Be sure to hop into the CodeByte community that I am building on Discord. Click here to join.

--

--