-
Notifications
You must be signed in to change notification settings - Fork 31
/
ast2json.py
46 lines (36 loc) · 1.02 KB
/
ast2json.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
import ast
import sys
import json
def classname(cls):
return cls.__class__.__name__
def jsonify_ast(node, level=0):
"""
https://github.com/maligree/python-ast-explorer/blob/master/parse.py
"""
fields = {}
for k in node._fields:
fields[k] = '...'
v = getattr(node, k)
if isinstance(v, ast.AST):
if v._fields:
fields[k] = jsonify_ast(v)
else:
fields[k] = classname(v)
elif isinstance(v, list):
fields[k] = []
for e in v:
fields[k].append(jsonify_ast(e))
elif isinstance(v, str):
fields[k] = v
elif isinstance(v, int) or isinstance(v, float):
fields[k] = v
elif v is None:
fields[k] = None
else:
fields[k] = 'unrecognized'
ret = { classname(node): fields }
return ret
with open(sys.argv[1]) as py_file:
code = py_file.read()
tree = ast.parse(code)
print(json.dumps(jsonify_ast(tree)))