Convert python AST to JSON Document

I’ve added my python2json.py script to github.

This is a small piece of the source code search algorithm project that I’ve been working on. I think this piece is useful in its own right, and that releasing it doesn’t impinge too much on the larger project.

As an example, let’s say we have the following code in example.py:

x = 1 + 2
print x

The script can be invoked with the -f option (or it can parse stdin) like so. You can pipe the output through json.tool like I do here to pretty-print the result:

./python2json.py -f example.py | python -mjson.tool

Will output:

{
    "_lineno": null,
    "node": {
        "_lineno": null,
        "spread": [
            {
                "_lineno": 2,
                "expr": {
                    "_lineno": 2,
                    "left": {
                        "_lineno": 2,
                        "type": "Const",
                        "value": "1"
                    },
                    "right": {
                        "_lineno": 2,
                        "type": "Const",
                        "value": "2"
                    },
                    "type": "Add"
                },
                "nodes": [
                    {
                        "_lineno": 2,
                        "name": "x",
                        "type": "AssName"
                    }
                ],
                "type": "Assign"
            },
            {
                "_lineno": 3,
                "nodes": [
                    {
                        "_lineno": 3,
                        "name": "x",
                        "type": "Name"
                    }
                ],
                "type": "Printnl"
            }
        ],
        "type": "Stmt"
    },
    "type": "Module"
}
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google