Transform a CSV file into a JSON file with Python

UPDATE: now on GitHub.



Here's the code. Create a file (for example) named csv2json.py with content:



import csv
import sys
import json

#EDIT THIS LIST WITH YOUR REQUIRED JSON KEY NAMES
fieldnames=["firstname","secondname","age"]

def convert(filename):
csv_filename = filename[0]
print "Opening CSV file: ",csv_filename
f=open(csv_filename, 'r')
csv_reader = csv.DictReader(f,fieldnames)
json_filename = csv_filename.split(".")[0]+".json"
print "Saving JSON to file: ",json_filename
jsonf = open(json_filename,'w')
data = json.dumps([r for r in csv_reader])
jsonf.write(data)
f.close()
jsonf.close()

if __name__=="__main__":
convert(sys.argv[1:])






USAGE:

python csv2json.py myCSVfile.txt

where myCSVfile.txt it's your CSV file (name it as you prefer).


It will create a JSON array in a file named myCSVfile.json

That's all.

Comments

Bruna said…
Can you tell me why the last element in my CSV file is my first element in my JSON file?
Antonio Pintus said…
Hi Bruna, can you write an example, please?
narayana p said…
Really good information to show through this blog. I really appreciate you for all the valuable information that you are providing us through your blog. python Online course