Skip to content

Instantly share code, notes, and snippets.

@pythononwheels
Created August 12, 2014 11:10
Show Gist options
  • Save pythononwheels/7631d8c8e3fadcb77393 to your computer and use it in GitHub Desktop.
Save pythononwheels/7631d8c8e3fadcb77393 to your computer and use it in GitHub Desktop.
Short python utility that converts a given csv to the according json. Fieldnames are taken from the first line of the csv.
import csv
import json
import sys
#
#
# converts csv to json
# fieldnames are taken from the first line of the csv input file
#
# khz / 2014
#
if __name__ == "__main__":
#print(sys.argv, len(sys.argv))
filename = None
if len(sys.argv) < 2:
print("usage: csv_to_json.py <filename> ")
print(" You dont need to give a file extension. The tool automatically adds .csv and .json")
sys.exit()
else:
filename = sys.argv[1]
csvfile = open(filename + '.csv', 'r', encoding="utf8")
fieldnames = list(csvfile.readline().split(","))
jsonfile = open(filename + '.json', 'w')
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
@pythononwheels
Copy link
Author

added an encoding to the open() call to make sure that python3 unicode errors wont occur.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment