Created
July 19, 2012 15:07
-
-
Save saml/3144569 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
import json | |
import csv | |
import sys | |
import codecs | |
import argparse | |
class UTF8Recoder: | |
""" | |
Iterator that reads an encoded stream and reencodes the input to UTF-8 | |
""" | |
def __init__(self, f, encoding): | |
self.reader = codecs.getreader(encoding)(f) | |
def __iter__(self): | |
return self | |
def next(self): | |
return self.reader.next().encode("utf-8") | |
class UnicodeReader: | |
""" | |
A CSV reader which will iterate over lines in the CSV file "f", | |
which is encoded in the given encoding. | |
""" | |
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): | |
f = UTF8Recoder(f, encoding) | |
self.reader = csv.reader(f, dialect=dialect, **kwds) | |
def next(self): | |
row = self.reader.next() | |
return [unicode(s, "utf-8") for s in row] | |
def __iter__(self): | |
return self | |
def to_json(input_file, output_file, encoding): | |
rows = UnicodeReader(input_file, encoding=encoding) | |
header = rows.next() | |
l = [] | |
for row in rows: | |
l.append(dict(zip(header, row))) | |
return json.dump(l, output_file, indent=2) | |
def main(argv): | |
parser = argparse.ArgumentParser(description='converts csv to json', prog=argv[0]) | |
parser.add_argument('input_file', help='path to csv input file') | |
parser.add_argument('--output', help='path to json output file [%(default)s]', default='-') | |
parser.add_argument('--encoding', help='character encoding of csv [%(default)s]', default='latin-1') | |
args = parser.parse_args(argv[1:]) | |
with open(args.input_file, 'rU') as input_file: | |
encoding = args.encoding | |
if args.output == '-': | |
output_file = sys.stdout | |
else: | |
output_file = open(args.output, 'w') | |
to_json(input_file, output_file, encoding) | |
if __name__ == '__main__': | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment