-
-
Save stennie/a39b087da394b746e4fe to your computer and use it in GitHub Desktop.
Convert results of a aggregate framework to CSV (http://stackoverflow.com/questions/12208771)
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 | |
def quoteStrings(strArr): | |
return ["'%s'"%k for k in strArr] | |
result = [ | |
{'_id': 'Rob', 'x': [12], 'y': [2], 'z': []}, | |
{'_id': 'George', 'x': [5], 'y': [3], 'z': [9]} | |
] | |
# open file and create csv writer | |
f = open('out.csv', 'w') | |
writer = csv.writer(f) | |
# flatten sub-arrays to double-quoted comma-separated strings, e.g. [1, 2, 3] ==> "1, 2, 3" | |
for i, row in enumerate(result): | |
for key in row: | |
if isinstance(row[key], list): | |
result[i][key] = ','.join([str(x) for x in row[key]]) | |
# write keys to csv | |
keys = [k for k in result[0].keys() if k!='_id'] | |
writer.writerow(quoteStrings(['Name'] + keys)) | |
for row in result: | |
writer.writerow(quoteStrings([row[k] for k in ['_id'] + keys])) | |
f.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment