-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2json.py
executable file
·48 lines (33 loc) · 932 Bytes
/
csv2json.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
#!/usr/bin/python
import csv, json, argparse, sys
result = {}
result_data = []
# Command line parsing
parser = argparse.ArgumentParser(description='Convert CSV to JSON')
parser.add_argument('-f','--fieldnames',
help='Field names')
parser.add_argument('-z','--zabbix',
action="store_true",
help='Format result for Zabbix LLD')
parser.add_argument('csvfile',
nargs='?',
type=argparse.FileType('r'),
default=sys.stdin)
args = parser.parse_args()
if args.fieldnames:
reader = csv.DictReader(args.csvfile, args.fieldnames.split(','))
else:
reader = csv.DictReader(args.csvfile)
if args.zabbix:
for row in reader:
new_key = ""
for key, value in row.items():
new_key = "{#%s}" % (key)
row[new_key] = row.pop(key)
result_data.append(row)
result["data"] = result_data
else:
for row in reader:
result_data.append(row)
result = result_data
print json.dumps(result, indent=4)