Created
August 9, 2018 09:49
-
-
Save pivstone/a6052127a1efdf84ce0c3450b63936ab to your computer and use it in GitHub Desktop.
Convert the Couchbase export csv file to truly CSV file
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 python3 | |
import sys | |
import csv | |
import json | |
file = sys.argv[1] | |
if (not file): | |
print('invalid args, need a file path') | |
exit(1) | |
def flattenjson( b, delim ): | |
val = {} | |
for i in b.keys(): | |
if isinstance( b[i], dict ): | |
get = flattenjson( b[i], delim ) | |
for j in get.keys(): | |
val[ i + delim + j ] = get[j] | |
else: | |
val[i] = b[i] | |
return val | |
input = [] | |
with open(file, 'r') as csvfile: | |
reader = csv.reader(csvfile) | |
next(reader, None) | |
for row in reader: | |
data = json.loads(row[4]) | |
data['id'] = row[0] | |
input.append(data) | |
input = [ flattenjson( x, "." ) for x in input] | |
columns = [ x for row in input for x in row.keys() ] | |
columns = list( set( columns ) ) | |
with open('out.csv', 'w') as out: | |
writer = csv.writer(out) | |
writer.writerow( columns ) | |
for i_r in input: | |
writer.writerow( map( lambda x: i_r.get( x, "" ), columns ) ) | |
print('done') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment