Esprima Python

4.0.1 · active · verified Wed Apr 15

Esprima Python is a Python port of the Esprima ECMAScript parser. It provides an ECMAScript (JavaScript) parsing infrastructure for multipurpose analysis in Python, generating a syntax tree that adheres to the SpiderMonkey AST format. The current version is 4.0.1, with releases typically following updates to the upstream JavaScript Esprima project or significant internal Python improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a simple JavaScript string using `esprima.parse()` and then converting the resulting Abstract Syntax Tree (AST) object to a Python dictionary for inspection. It also shows how to catch parsing-specific exceptions.

import esprima

js_code = "var answer = 42; console.log(answer);"

try:
    # Parse the JavaScript code
    tree = esprima.parse(js_code, options={'loc': True, 'range': True})

    # The 'tree' object is an AST. It can be converted to a dictionary.
    ast_dict = tree.to_dict()

    # Print a part of the AST (e.g., the first statement's type)
    if ast_dict and 'body' in ast_dict and len(ast_dict['body']) > 0:
        print(f"Parsed statement type: {ast_dict['body'][0]['type']}")

    # Example of accessing tokens (if options={'tokens': True} was used)
    # tokens = esprima.tokenize(js_code)
    # print(f"First token: {tokens[0].to_dict()}")

except esprima.error.EsprimaException as e:
    print(f"Parsing error: {e}")

view raw JSON →