-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparse_graphql.py
90 lines (67 loc) · 2.14 KB
/
parse_graphql.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
79
80
81
82
83
84
85
86
87
88
89
90
from parsimonious.grammar import Grammar
import json
grammar = Grammar("""
root = WS object_name WS OPEN_ROUND WS object_id WS CLOSE_ROUND WS WS object WS
object = OPEN_CURLY WS field_list WS CLOSE_CURLY
WS = ~"\s*"
OPEN_CURLY = "{"
CLOSE_CURLY = "}"
OPEN_ROUND = "("
CLOSE_ROUND = ")"
COMMA = ","
object_name = ~"[A-Z0-9]*"i
object_id = ~"[A-Z0-9]*"i
name = ~"[A-Z0-9]*"i
field_name = ~"[A-Z0-9]*"i
field_list = field WS (COMMA WS field)*
field = field_name WS optional_object
optional_object = object?
""")
# print ast
#convert to a python dict
IGNORE_NAMES = ['WS', 'OPEN_CURLY', 'CLOSE_CURLY', 'COMMA', 'OPEN_ROUND', 'CLOSE_ROUND']
split_list = lambda lst: (lst[0], lst[1:])
def filter_tokens(node):
return node.expr_name not in IGNORE_NAMES
def convert_field(ast):
(field_name, _, optional_object) = ast
child_fields = [] if len(optional_object.children) == 0 else (
convert_object(optional_object.children[0])
)
return {
'field_name': field_name.text,
'child_fields': child_fields
}
def convert_object(ast):
print 'convert_object'
head, rest = filter(filter_tokens, filter(filter_tokens, ast.children)[0])
map(lambda x: filter(filter_tokens, x.children)[0], rest.children)
fields = [head] + map(lambda x: filter(filter_tokens, x.children)[0],
rest.children)
fields = [convert_field(field) for field in fields]
return fields
def convert_root_object(ast):
(object_name, object_id, my_object) = filter(filter_tokens, ast.children)
return {
object_name.text: {
'fields': convert_object(my_object),
'id': object_id.text
}
}
# output = convert_root_object(ast)
# print json.dumps(output, indent=4)
def parse_graphql(graphql):
#eg:
#graphql = """
# User (234234) {
# one {
# sub1,
# sub2
# },
# two,
# three,
# four
# }
#"""
ast = grammar.parse(graphql)
return convert_root_object(ast)