CodeByte
Published in

CodeByte

CSV to JSON converter in 10 lines of code

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store