求Python代码:获取GraphQL查询中指定字段的路径列表
获取GraphQL查询中指定字段的路径(Python实现)
直接用graphql-core库解析GraphQL查询的抽象语法树(AST)是最可靠的方案,能避免手动处理字符串带来的各种边界问题。
步骤1:安装依赖
pip install graphql-core
步骤2:实现代码
from graphql import parse, visit, FieldNode def get_field_paths(query_str, target_field): paths = [] # 将查询字符串解析为GraphQL抽象语法树 document = parse(query_str) def enter_field(node, key, parent, path, ancestors): # 匹配目标字段节点 if isinstance(node, FieldNode) and node.name.value == target_field: # 从祖先节点中提取字段路径 field_path = [] for ancestor in ancestors: if isinstance(ancestor, FieldNode): field_path.append(ancestor.name.value) # 添加当前目标字段到路径末尾 field_path.append(target_field) paths.append(field_path) # 遍历AST所有节点,收集匹配路径 visit(document, enter={FieldNode: enter_field}) return paths # 测试示例 if __name__ == "__main__": query = ''' query { books { __typename title } users { __typename name age } } ''' # 获取__typename的所有路径 result = get_field_paths(query, "__typename") print(result) # 输出: [['books', '__typename'], ['users', '__typename']]
代码说明
- AST解析:
parse()函数把查询字符串转换成机器可理解的抽象语法树,这是处理GraphQL查询的标准方式,能兼容多层嵌套、片段、变量等复杂查询结构。 - 节点遍历:
visit()函数遍历AST的所有节点,我们只聚焦FieldNode类型(即查询中的字段节点)。 - 路径构建:通过
ancestors参数获取当前字段的所有父级字段,拼接成完整路径后收集到结果列表中。
该方案也支持多层嵌套的字段场景:
nested_query = ''' query { books { author { __typename name } } } ''' print(get_field_paths(nested_query, "__typename")) # 输出: [['books', 'author', '__typename']]
内容的提问来源于stack exchange,提问作者alireza bodaghi
相关产品推荐
相关产品推荐

