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.
asty Command-Line Toolasty tool converts Go source files to an AST in JSON format (and vice versa). - Install the
astytool:This command installs the executable to your$GOPATH/bindirectory. - Convert a Go file to JSON:
Navigate to your source code directory and run thego2jsoncommand:Replace<input.go>with the name of your Go source file and<output.json>with the desired output file name.
asty Libraryasty 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
g10z3r/asonason library is another tool designed for serializing Go ASTs into JSON and deserializing them back, simplifying the process of analysis and modification. - GitHub Repository: g10z3r/ason
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 ↓
func main() {
if x > 0 {
fmt.Println("positive")
} else {
fmt.Println("non-positive")
}
}Existing experiments
- Oden (discontinued) — was a Lisp-like language targeting Go
- Have — https://github.com/piotr-skotnicki/have — experimental indentation-based Go alternative
- Og — https://github.com/piot/og — "Offside Go", uses indentation instead of braces
Have (Python-like syntax transpiling to Go)
- GitHub: https://github.com/vrok/have
- Website: http://havelang.org (may be defunct now)
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:
- Oden — functional language that compiled to Go (discontinued): https://github.com/oden-lang/oden
- GopherJS — Go to JavaScript: https://github.com/gopherjs/gopherjs
- c2go — C to Go transpiler: https://github.com/elliotchance/c2go
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).