Created
August 20, 2015 18:47
-
-
Save awesomebjt/713965cd27a4257e30d7 to your computer and use it in GitHub Desktop.
CSV to JSON in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import json | |
import sys | |
#Expects argument 1 to be a .csv filename. Matching file ending in .json is written. | |
if sys.argv[1] is not None and len(sys.argv[1])>0: | |
infile = open(sys.argv[1],'r') | |
outfile = open(sys.argv[1].replace(".csv",".json"),'w') | |
reader = csv.reader(infile) | |
colnames = [] | |
output_array = [] | |
for row in reader: | |
out_dict = {} | |
if reader.line_num == 1: #Assume the columns have names. | |
colnames = row | |
else: | |
for colnum in range(len(row)): | |
out_dict[colnames[colnum]] = row[colnum] | |
output_array.append(out_dict) | |
outfile.write(json.dumps(output_array)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment