Sunday, February 01, 2026

Go AST (code <=> JSON)

To convert a Go program's Abstract Syntax Tree (AST) to JSON, you can use third-party command-line tools or Go packages. A popular choice is the asty tool, which offers a straightforward command-line interface and library for this purpose. 

Using the asty Command-Line Tool
The asty tool converts Go source files to an AST in JSON format (and vice versa). 
  1. Install the asty tool:
    bash
    go install github.com
    
    This command installs the executable to your $GOPATH/bin directory.
  2. Convert a Go file to JSON:
    Navigate to your source code directory and run the go2json command:
    bash
    asty go2json -input <input.go> -output <output.json>
    
    Replace <input.go> with the name of your Go source file and <output.json> with the desired output file name. 
Using Go Packages Programmatically
You can also use Go libraries within your own program to parse Go code and generate a JSON representation of its AST. 
Option 1: Using the asty Library
The asty library allows programmatic conversion of Go AST to JSON, providing a structure very close to real Go structs. 
  • GitHub Repository: asty-org/asty
  • Go Packages Documentation: pkg.go.dev/github.com/asty-org/asty 


Option 2: Using g10z3r/ason
The ason library is another tool designed for serializing Go ASTs into JSON and deserializing them back, simplifying the process of analysis and modification. 
These tools facilitate working with the Go AST outside of the standard library, which primarily uses the go/parser and go/ast packages without built-in direct JSON serialization. 

Why Go requires braces

Go's grammar is designed for fast, unambiguous parsing. The braces aren't just style — they're part of how the compiler avoids lookahead complexity. Semicolons are auto-inserted based on line endings, and braces delimit where statements begin/end unambiguously.

Theoretical alternatives

You could build a preprocessor or transpiler that converts indentation-based syntax to Go:

// Hypothetical "GoLite"
func main()
    if x > 0
        fmt.Println("positive")
    else
        fmt.Println("non-positive")

↓ transpiles to ↓

go
func main() {
    if x > 0 {
        fmt.Println("positive")
    } else {
        fmt.Println("non-positive")
    }
}

Existing experiments

Have (Python-like syntax transpiling to Go)

I apologize for the earlier broken link. The project I incorrectly named "Have" with a different author doesn't exist — there's only this one by vrok.

As for "Og" (Offside Go), my searches didn't find a current repository for it — it may have been an experimental project that's since been removed or renamed.

Other alternatives that do exist:

If you're interested in the braceless/indentation concept, Have is the most direct example, though it appears to be unmaintained (last commits were several years ago).