Created
September 25, 2012 15:16
-
-
Save flashingpumpkin/3782533 to your computer and use it in GitHub Desktop.
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 | |
""" | |
Makes JSON files out of CSV files. | |
""" | |
import argparse | |
import csv | |
import json | |
parser = argparse.ArgumentParser(description = "Turns a CSV file into JSON") | |
parser.add_argument('file', action = 'store') | |
parser.add_argument('-i', '--index', action='append', nargs=2, help="Use to add custom name to columns, ie `--index 1 FirstName --index 2 LastName --index 3 Email`. If unnamed columns are encountered, they'll receive a default key of `column-<number>`.", metavar=("COL", "NAME"), default = []) | |
parser.add_argument('--indent', action='store', type = int, help = "How to indent the JSON", default = 1) | |
args = parser.parse_args() | |
def main(): | |
reader = csv.reader(open(args.file)) | |
lines = [] | |
try: | |
while True: | |
lines.append(reader.next()) | |
except StopIteration: | |
pass | |
keys = lines[0] | |
lines = lines[1:] | |
for (idx, name) in args.index: | |
keys[int(idx)] = name | |
keys = map(lambda k: k.lower(), keys) | |
for (i, key) in enumerate(keys): | |
if not key: | |
keys[i] = 'column-{}'.format(i) | |
data = map(lambda line: dict(zip(keys, line)), lines) | |
print json.dumps(data, indent = args.indent) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment