-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjson-structure
More file actions
executable file
·51 lines (32 loc) · 1.06 KB
/
json-structure
File metadata and controls
executable file
·51 lines (32 loc) · 1.06 KB
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
#!/usr/bin/env python3
import json
import sys
from numbers import Number
def typed_dedupe(x):
if isinstance(x, (list, tuple)):
return ("list", tuple(set(tuple(map(typed_dedupe, x)))))
if isinstance(x, dict):
return ("dict", tuple((key, typed_dedupe(value)) for key, value in x.items()))
if isinstance(x, Number):
return ("type", "number")
if isinstance(x, str):
return ("type", "string")
if isinstance(x, bool):
return ("type", "bool")
if x is None:
return ("type", "null")
raise ValueError(f"unexpected type for {x}")
def build_struct(info):
kind, sub_info = info
if kind == "dict":
return {key: build_struct(value) for key, value in sub_info}
if kind == "list":
return list(map(build_struct, sub_info))
return sub_info
def obj_struct(x):
return build_struct(typed_dedupe(x))
if len(sys.argv) == 2 and sys.argv[1] == "-l":
data = list(map(json.loads, sys.stdin))
else:
data = json.load(sys.stdin)
print(json.dumps(obj_struct(data), indent=2))