-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconvertToCSV.py
66 lines (57 loc) · 1.77 KB
/
convertToCSV.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# for python 3
import demjson
import sys
import os
# Create basic tree structure
header = '"id","value"'
result = []
path = []
# The main convertion function
def recognize(obj):
if isinstance(obj, list):
for k in range(len(obj)):
path.append(str(k))
result.append('"' + ('.'.join(path)) + '",')
recognize(obj[k])
path.pop()
elif isinstance(obj, dict):
for k, v in obj.items():
path.append(str(k))
result.append('"' + ('.'.join(path)) + '",')
recognize(v)
path.pop()
else:
result[-1] += ('"' + str(obj) + '"')
def main():
# Parse file spec
file = sys.argv[1]
filename = sys.argv[1].split('/')[-1].replace('.json','')
# Load File to Variavble: jsondoc
try:
print(file)
with open(file, 'r', encoding='utf-8') as f:
jsondoc = demjson.decode(f.read())
except Exception as e:
exit("Error occurs when loading: '{0}'".format(e))
# Convert it!
result.append('"'+filename+'",')
path.append(filename)
recognize(jsondoc)
result.insert(0, header)
# Write file
## Create "output" folder if no exists
if not os.path.exists(os.path.dirname('./output/')):
try:
os.makedirs(os.path.dirname('./output/'))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
## Write to ./output/output.csv
try:
with open('./output/output.csv', 'w') as o:
o.writelines(map(lambda x: x+"\n", result))
exit("File conversion was completed without errors.")
except Exception as e:
exit("Error occurs when writing: '{0}'".format(e))
if __name__ == "__main__":
main()