You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中遍历Esprima生成的JSX组件AST节点并访问父子节点

解决Python遍历Esprima生成的JSX AST节点并访问父子节点的问题

因为esprima-ast-visitor版本过旧,不支持现代JS的节点类型(比如ImportDeclaration),你可以自己写一个简单的递归遍历函数,直接操作JSON格式的AST,同时轻松访问每个节点的父节点和子节点,完全适合Python新手。

步骤1:加载AST JSON文件

首先用Python内置的json模块加载序列化后的AST文件:

import json

# 替换成你的AST JSON文件路径
with open('jsx_ast.json', 'r', encoding='utf-8') as f:
    ast = json.load(f)

步骤2:编写递归遍历函数

这个函数会递归遍历每个节点,每次传递当前节点和它的父节点,同时处理不同类型的子节点(列表或单个字典节点):

def traverse_ast(node, parent_node=None):
    if not node:
        return
    
    # 获取当前节点和父节点的类型(方便调试)
    current_type = node.get('type', '未知节点类型')
    parent_type = parent_node.get('type', '根节点') if parent_node else '根节点'
    print(f"当前节点:{current_type} | 父节点:{parent_type}")

    # 定义Esprima AST中常见的子节点属性,可根据你的AST结构补充
    child_attrs = [
        'body', 'declarations', 'arguments', 'children', 'expression',
        'left', 'right', 'callee', 'init', 'specifiers', 'imported',
        'local', 'source'
    ]

    # 遍历所有可能的子节点属性
    for attr in child_attrs:
        child = node.get(attr)
        if isinstance(child, list):
            # 处理列表类型的子节点(比如多个语句组成的body)
            for item in child:
                traverse_ast(item, node)
        elif isinstance(child, dict):
            # 处理单个字典类型的子节点(比如某个表达式节点)
            traverse_ast(child, node)

步骤3:调用遍历函数

从AST的根节点开始遍历:

traverse_ast(ast)

自定义节点处理逻辑

如果需要针对特定节点(比如ImportDeclaration)做操作,直接在函数里添加判断即可:

def traverse_ast(node, parent_node=None):
    if not node:
        return
    
    current_type = node.get('type', '未知节点类型')
    parent_type = parent_node.get('type', '根节点') if parent_node else '根节点'
    
    # 处理ImportDeclaration节点
    if current_type == 'ImportDeclaration':
        source_path = node.get('source', {}).get('value')
        print(f"找到导入声明:{source_path},父节点类型:{parent_type}")
    
    # 后续遍历子节点的逻辑和之前一样
    child_attrs = [
        'body', 'declarations', 'arguments', 'children', 'expression',
        'left', 'right', 'callee', 'init', 'specifiers', 'imported',
        'local', 'source'
    ]

    for attr in child_attrs:
        child = node.get(attr)
        if isinstance(child, list):
            for item in child:
                traverse_ast(item, node)
        elif isinstance(child, dict):
            traverse_ast(child, node)

为什么这个方法适合新手?

  • 完全基于Python基础语法(递归、字典、列表操作),不需要依赖第三方库,避免版本兼容问题。
  • 代码逻辑清晰,你可以直观看到每个节点的父子关系,还能根据自己的需求随时扩展子节点属性列表。
  • 调试方便,通过打印节点类型就能快速理解AST的结构。

内容的提问来源于stack exchange,提问作者Big boy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:37:06