Created
December 6, 2013 23:45
-
-
Save nside/7834110 to your computer and use it in GitHub Desktop.
converts a stream from JSON to CSV
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, json, sys, cStringIO, codecs | |
from operator import itemgetter | |
def fmt(s): | |
if s == None: | |
return '' | |
elif isinstance(s, basestring): | |
return s.encode('utf-8') | |
else: | |
return unicode(s) | |
csv.register_dialect('psql', quoting=csv.QUOTE_ALL) | |
class UnicodeWriter: | |
""" | |
A CSV writer which will write rows to CSV file "f", | |
which is encoded in the given encoding. | |
""" | |
def __init__(self, f, dialect='psql', encoding="utf-8", **kwds): | |
# Redirect output to a queue | |
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([fmt(s) for s in row]) | |
# Fetch UTF-8 output from the queue ... | |
data = self.queue.getvalue() | |
data = data.decode("utf-8") | |
# ... and reencode it into the target encoding | |
data = self.encoder.encode(data) | |
# write to the target stream | |
self.stream.write(data) | |
# empty queue | |
self.queue.truncate(0) | |
def writerows(self, rows): | |
for row in rows: | |
self.writerow(row) | |
writer = UnicodeWriter(sys.stdout) | |
headers = [] | |
access = None | |
for row in sys.stdin: | |
j = json.loads(row) | |
if not headers: | |
headers = j.keys() | |
writer.writerow(headers) | |
access = itemgetter(*headers) | |
else: | |
writer.writerow(access(j)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment