Created
November 25, 2012 07:53
-
-
Save samba/4142772 to your computer and use it in GitHub Desktop.
Very simple CSV to JSON converter
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 | |
# Very simple CSV to JSON converter | |
# Supports CSV labels | |
# Usage: | |
# (without labels) | |
# csv-to-json.py ./data.csv > ./data.json | |
# like: [ [ 1, 2, 3 ] ] | |
# (with labels) | |
# csv-to-json.py -l ./data.csv > ./data.json | |
# like: [ { one: 1, two: 2, three: 3 } ] | |
# | |
import json | |
import csv | |
import sys | |
def converter(filename, labels): | |
with open(filename, 'rb') as buf: | |
dialect = csv.Sniffer().sniff(buf.read(1024)) | |
buf.seek(0); | |
if labels: | |
reader = csv.DictReader(buf, dialect = dialect) | |
else: | |
reader = csv.reader(buf, dialect = dialect) | |
return json.dumps(list(reader)) | |
class Options(object): | |
labels = False; | |
def __init__(self, args): | |
for i in args: | |
if i == '-l': | |
self.labels = True; | |
else: | |
self.filename = i; | |
def main(options): | |
print converter(options.filename, options.labels) | |
if __name__ == '__main__': | |
main(Options(sys.argv)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment