Last active
December 22, 2015 22:49
-
-
Save johnjreiser/6542710 to your computer and use it in GitHub Desktop.
script to convert a CSV file to JSON
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
#!/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