Sunday, December 24, 2023

Python AST <=> JSON

Python language comes with "batteries included", many useful modules / libraries

ast — Abstract Syntax Trees — Python 3.12.1 documentation

ast2json · PyPI

json2ast · PyPI

Here is an example that does full "round-trip" 
python code text => ast => json => ast => code text

import ast
import json
from ast2json import ast2json
from json2ast import json2ast

code_text="""
def hello(name):
   print("Hello ", name) hello('World')
"""
print('=== code text ===\n', code_text)

ast_from_code=ast.parse(code_text)
print('=== ast from code ===\n', ast.dump(ast_from_code, indent=4))

json_from_ast = ast2json(ast_from_code)
print('=== json from ast ===\n', json.dumps(json_from_ast, indent=2))

ast_from_json = json2ast(json_from_ast)
print('=== ast from json ===\n', ast.dump(ast_from_json, indent=4))

code_from_ast = ast.unparse(ast_from_json)
print('=== code from ast ===\n', code_from_ast)

interesting: after "round-trip" double quotes from "Hello" from print statement are converted to single quotes. Python "likes" single quotes more :)


No comments: