-
-
Save cmscardoso/9c1c88140c006a3c015575f5b9cd3903 to your computer and use it in GitHub Desktop.
Basic conversion of a JSON [{"a":"b",…},{"a":"c",…}] to csv.
This file contains hidden or 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 | |
| # coding=utf-8 | |
| import json | |
| import sys | |
| import codecs | |
| import csv,codecs,cStringIO | |
| class UTF8Recoder: | |
| 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: | |
| def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **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 | |
| class UnicodeWriter: | |
| def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds): | |
| self.queue = cStringIO.StringIO() | |
| self.writer = csv.writer(self.queue, dialect=dialect, **kwds) | |
| self.stream = f | |
| self.encoder = codecs.getincrementalencoder(encoding)() | |
| def writerow(self, row): | |
| self.writer.writerow([s.encode("utf-8") for s in row]) | |
| data = self.queue.getvalue() | |
| data = data.decode("utf-8") | |
| data = self.encoder.encode(data) | |
| self.stream.write(data) | |
| self.queue.truncate(0) | |
| def writerows(self, rows): | |
| for row in rows: | |
| self.writerow(row) | |
| j = "" | |
| with codecs.open(sys.argv[1], "r", "utf-8") as f: | |
| j = json.loads(f.read()) | |
| f = sys.argv[1]+".csv" | |
| print f | |
| fout = open(f,'wb') | |
| writer = UnicodeWriter(fout,quoting=csv.QUOTE_ALL) | |
| for item in j: | |
| # print item.values() | |
| writer.writerow(item.values()) | |
| fout.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment