-
Notifications
You must be signed in to change notification settings - Fork 1
/
ks2json.py
executable file
·79 lines (62 loc) · 1.89 KB
/
ks2json.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
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
import sys
assert sys.version_info[0] == 3
import types
import kaitaistruct
import kshelp
filterLevel = 0
#------------------------------------------------------------------------------
# text dumping stuff
#------------------------------------------------------------------------------
def dump(obj, depth=0):
global filterLevel
print('%s{' % ('\t'*depth))
depth += 1
print('%s"_kaitai_type": "%s",' % (('\t'*depth), kshelp.objToStr(obj)))
kshelp.exercise(obj)
fieldNamesPrint = kshelp.getFieldNamesPrint(obj, filterLevel)
fieldNamesDescend = kshelp.getFieldNamesDescend(obj, filterLevel)
fieldNamesAll = fieldNamesPrint + fieldNamesDescend
for (i,fieldName) in enumerate(fieldNamesAll):
subObj = None
try:
subObj = getattr(obj, fieldName)
except Exception:
continue
if subObj == None:
continue
# simple fields
if fieldName in fieldNamesPrint:
subObjStr = kshelp.objToStr(subObj)
print('%s"%s": "%s"' % (('\t'*depth), fieldName, subObjStr), end='')
# kaitai struct (descend!)
else:
if isinstance(subObj, list):
print('%s"%s":\n%s[' % (('\t'*depth), fieldName, ('\t'*depth)))
for (j, tmp) in enumerate(subObj):
#print('%s.%s[%d]:' % (('\t'*depth), fieldName, i))
dump(tmp, depth+1)
if j!=len(subObj)-1:
print(',')
else:
print('')
print('%s]' % ('\t'*depth), end='')
else:
print('%s"%s":' % (('\t'*depth), fieldName))
dump(subObj, depth)
# add comma?
if i!=len(fieldNamesAll)-1:
print(',')
else:
print('')
depth -= 1
print('%s}' % ('\t'*depth), end='')
#------------------------------------------------------------------------------
# main
#------------------------------------------------------------------------------
if __name__ == '__main__':
assert len(sys.argv) == 3
filterLevel = int(sys.argv[1])
fpath = sys.argv[2]
parsed = kshelp.parseFpath(fpath)
dump(parsed, filterLevel)