-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjson2csv.py
More file actions
42 lines (33 loc) · 1017 Bytes
/
json2csv.py
File metadata and controls
42 lines (33 loc) · 1017 Bytes
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
import json
import argparse
def get_ballot(record, words):
x = record
if words is not None:
words = words.split(".")
for word in words:
try:
x = x[word]
except Exception as e:
print(record)
raise e
return x
def get_csv(data, slug, words=None):
x = data[slug]
candidates = list(get_ballot(x[0], words).keys())
records = []
records.append(",".join(candidates))
for record in x:
o = []
record = get_ballot(record, words)
for candidate in candidates:
o.append(record[candidate])
records.append(",".join(o))
print("\n".join(records))
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument('--slug', nargs='?')
p.add_argument('--prefix', nargs='?')
p.add_argument('ballots', type=argparse.FileType('r'))
args = p.parse_args()
ballots = json.load(args.ballots)
get_csv(ballots, args.slug, args.prefix)