-
Notifications
You must be signed in to change notification settings - Fork 0
/
json2tsv
executable file
·67 lines (63 loc) · 1.62 KB
/
json2tsv
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
67
#!/usr/bin/env python
import sys, getopt, json
from types import NoneType
def usage(name):
print 'Usage: %s -l [key1:key2] -t [text1] -f [field1] -f [field2] ... -t [textN] -f [fieldN]' % name
def main(argv):
fields = []
nodeAddr = ''
try:
opts, args = getopt.getopt(argv[1:],'hl:f:t:')
except getopt.GetoptError:
usage(argv[0])
sys.exit(2)
for opt, arg in opts:
if opt in ('-h'):
usage(argv[0])
sys.exit()
elif opt in ('-f'):
fields.append(['f', arg])
elif opt in ('-t'):
fields.append(['t', arg])
elif opt in ('-l'):
nodeAddr = arg
if not nodeAddr or not fields:
usage(argv[0])
sys.exit(1)
pipe = sys.stdin.read()
try:
payload = json.loads(pipe)
except:
print 'Err: unable to parse JSON'
sys.exit(1)
nodeList = nodeAddr.split(':')
data = []
for i in nodeList:
if i in payload.keys():
data = payload[i]
else:
print 'Err: unable to find a list "%s"' % nodeAddr
sys.exit(1)
for i in data:
line = []
for j in fields:
if j[0] is 't':
line.append(j[1])
elif j[0] is 'f':
if j[1] in i.keys():
if isinstance(i[j[1]], unicode):
hay = i[j[1]].replace('\t', ' ')
elif isinstance(i[j[1]], (int, float)):
hay = str(i[j[1]])
elif isinstance(i[j[1]], NoneType):
hay = 'NULL'
else:
hay = i[j[1]]
line.append(hay)
else:
print 'Err: unable to find a field "%s"' % j
sys.exit(1)
print u'\t'.join(line).encode('utf-8')
sys.exit()
if __name__ == "__main__":
main(sys.argv)