Skip to content

Instantly share code, notes, and snippets.

@johnjreiser
Last active December 22, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnjreiser/6542710 to your computer and use it in GitHub Desktop.
Save johnjreiser/6542710 to your computer and use it in GitHub Desktop.
script to convert a CSV file to JSON
#!/usr/bin/env python
import csv
import simplejson as json
import sys, os
rows = {}
csvkey = "mun_code"
# csvkey is the CSV column that contains a unique ID
exflds = ('',)
# exflds contains a list of CSV fields to exclude from the JSON
if len(sys.argv) == 2:
if os.path.exists(sys.argv[1]):
fn = sys.argv[1]
else:
raise "File not found."
else:
raise "Insufficient parameters."
with open(fn, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row[csvkey] not in muni:
# skip record if a CSV record with the same csvkey has already been processed
rd = {}
for field in reader.fieldnames:
if field not in exflds:
# ignore the fields listed in the exflds list
rd[field] = row[field]
rows[row[csvkey]] = rd
print json.dumps(rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment