我知道如何通过库将 python 转换ast为jsonast2json
import ast
from ast2json import ast2json
node = ast.parse("2+3", mode='eval')
e = eval(compile(node,'<string>','eval')) # equals
node_j = ast2json(node)
Run Code Online (Sandbox Code Playgroud)
这给了我这个对象
{'_type': 'Expression',
'body': {'_type': 'BinOp',
'col_offset': 0,
'left': {'_type': 'Num', 'col_offset': 0, 'lineno': 1, 'n': 2},
'lineno': 1,
'op': {'_type': 'Add'},
'right': {'_type': 'Num', 'col_offset': 2, 'lineno': 1, 'n': 3}}}
Run Code Online (Sandbox Code Playgroud)
但如何将node_j对象转换回ast对象呢?
有一个相反方向的转换工具,json2ast https://pypi.org/project/json2ast/
“这个包的工作方向与 ast2json 包相反,后者采用 Python AST 对象作为输入并生成 JSON 结构作为输出。json2ast 函数需要一个由 ast2json 创建的 Python 字典并返回 AST 的复制用于创建该字典的对象。”
https://pypi.org/project/ast2json/