-
Notifications
You must be signed in to change notification settings - Fork 17
/
infer_json.py
57 lines (53 loc) · 1.66 KB
/
infer_json.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
import json
import sys
from pprint import pprint
DEFINITIONS = set()
UNFINISHED = []
def deep_type(data, optional_type=""):
if isinstance(data, dict):
return optional_type
elif isinstance(data, list):
if not data:
UNFINISHED.append(data)
return 'Still Unknown'
if isinstance(data[0], dict):
label = " ".join(data[0].keys())
else:
label = deep_type(data[0])
return 'List[{}]'.format(label)
elif isinstance(data, unicode):
return 'str'
else:
return data.__class__.__name__
def guess_schema(key, input):
if isinstance(input, dict):
DEFINITIONS.add(
tuple(
[key, tuple([(k, deep_type(v, k)) for k,v in input.items()])]
)
)
return {str(key.encode('ascii', 'replace').decode('ascii')):
guess_schema(key, value) for key, value in input.items()}
elif isinstance(input, list):
if not input:
UNFINISHED.append(key)
return 'list'
if isinstance(input[0], dict):
label = " ".join(input[0].keys())
else:
label = str(len(input))
return [guess_schema(label, input[0])] if input else []
else:
return deep_type(input)
if __name__ == '__main__':
pprint(guess_schema(sys.argv[1].split('.')[-2], json.load(open(sys.argv[1]))))
'''
print "structures:"
for label, fields in DEFINITIONS:
print " - name:", label
print " fields:"
for name, type in fields:
print ' - name:', name
print ' type:', type
'''
#pprint(DEFINITIONS)