JavaScript parser in Python - Stack Overflow
A good javascript/typescript parser in Python
Are you seeking artists or developers to help you with your game? We run a monthly game jam in this Discord where we actively pair people with other creators.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
More on reddit.comlibrary - TypeScript compiler for Python - Software Recommendations Stack Exchange
Typing for JSON Payloads
Videos
» npm install @qoretechnologies/python-parser
» npm install dt-python-parser
Nowadays, there is at least one better tool, called slimit:
SlimIt is a JavaScript minifier written in Python. It compiles JavaScript into more compact code so that it downloads and runs faster.
SlimIt also provides a library that includes a JavaScript parser, lexer, pretty printer and a tree visitor.
Demo:
Imagine we have the following javascript code:
$.ajax({
type: "POST",
url: 'http://www.example.com',
data: {
email: '[email protected]',
phone: '9999999999',
name: 'XYZ'
}
});
And now we need to get email, phone and name values from the data object.
The idea here would be to instantiate a slimit parser, visit all nodes, filter all assignments and put them into the dictionary:
from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor
data = """
$.ajax({
type: "POST",
url: 'http://www.example.com',
data: {
email: '[email protected]',
phone: '9999999999',
name: 'XYZ'
}
});
"""
parser = Parser()
tree = parser.parse(data)
fields = {getattr(node.left, 'value', ''): getattr(node.right, 'value', '')
for node in nodevisitor.visit(tree)
if isinstance(node, ast.Assign)}
print fields
It prints:
{'name': "'XYZ'",
'url': "'http://www.example.com'",
'type': '"POST"',
'phone': "'9999999999'",
'data': '',
'email': "'[email protected]'"}
ANTLR, ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages.
The ANTLR site provides many grammars, including one for JavaScript.
As it happens, there is a Python API available - so you can call the lexer (recognizer) generated from the grammar directly from Python (good luck).
I'm officially losing it. I spent the past 2 days looking for a javascript/typescript parser in Python. Most of the ones I found are outdated and incompatible with current updates, as arrowfunctions and regular notations give errors. The use case for this is being able to scan an entire codebase in JS/TS and extracting valuable info such as variable names, classes, methods, invocations, etc...