Skip to content

Instantly share code, notes, and snippets.

@Dannyzen
Created May 5, 2014 02:02
Show Gist options
  • Save Dannyzen/8d5457f0f1bb9d06c508 to your computer and use it in GitHub Desktop.
Save Dannyzen/8d5457f0f1bb9d06c508 to your computer and use it in GitHub Desktop.
For turning a csv into a json file
import csv
import sys
import json
#Add the CSV headers into the fieldnames array
fieldnames=['changethis','changethis2','changethis3']
def convert(filename):
csv_filename = filename[0]
print "Opening CSV: ",csv_filename
f=open(csv_filename, 'r')
csv_reader = csv.DictReader(f,fieldnames)
json_filename = csv_filename.split(".")[0]+".json"
print "Saving JSON: ",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:])
#Then to eat that json data:
import json
from pprint import pprint
json_data=open('json_data')
data = json.load(json_data)
for item in data:
print item["changethiskey"]
#given a csv of:
#changethiskey
#1
#this should print 1
@Dannyzen
Copy link
Author

Dannyzen commented May 6, 2014

these are both in python

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