Skip to content

Instantly share code, notes, and snippets.

@geotheory
Created August 17, 2015 14:44
Show Gist options
  • Save geotheory/4c66bc442eb7baaa4374 to your computer and use it in GitHub Desktop.
Save geotheory/4c66bc442eb7baaa4374 to your computer and use it in GitHub Desktop.
CSV to JSON Python script
import json
import sys
print sys.argv[1]
f = open(sys.argv[1],'r')
arr=[]
headers = []
for header in f.readline().split(','):
headers.append(header)
# replace characters that can be problematic in JSON category names
headers = [h.replace('-', '_') for h in headers]
headers = [h.replace(' ', '_') for h in headers]
headers = [h.replace('.', '_') for h in headers]
for line in f.readlines():
lineItems = {}
for i,item in enumerate(line.split(',')):
lineItems[headers[i]] = item
arr.append(lineItems)
f.close()
jsonText = json.dumps(arr)
print jsonText
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment