Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Convert results of a aggregate framework to CSV (http://stackoverflow.com/questions/12208771)
#!/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
Something went wrong with that request. Please try again.