How to convert Antlr parse tree to JSON

475 views
Skip to first unread message

Gervasius Ishuuwa

unread,
Aug 22, 2019, 1:18:21 PM8/22/19
to golang-nuts
Hi Guys, 

I am trying to replicate the following solution (https://stackoverflow.com/questions/49116223/convert-antlr-parse-tree-to-json) in Golang. 
The expected ouput is a nested JSON with this structure:

{
    "VeloContext": [
        {
            "AuthorContext": [
                {
                    "...": [
                        {
                            "type": 7,
                            "text": "..."
                        }
                    ]
                }
            ],
            "OrchestrationContext":[
                {...}
            ]
        }
    ]
}
But getting the root node only, instead.
{
    "VeloContext":{}
}

I have attached a snapshot of my parse tree and debug output. Below is my code thus far:

package main

import (
"encoding/json"
"reflect"
"strconv"
"strings"
"time"
"../parser"
)

func toMap(tree antlr.Tree) *linkedhashmap.Map {
m := linkedhashmap.New()
traverseMap(tree, m)
return m
}

func traverseMap(tree antlr.Tree, m *linkedhashmap.Map) {
if (reflect.TypeOf(tree) == reflect.TypeOf(&antlr.TerminalNodeImpl{})) {
token := tree.(antlr.TerminalNode).GetSymbol()
m.Put("type", token.GetTokenType())
m.Put("text", token.GetText())

} else {
children := arraylist.New()
s := reflect.ValueOf(tree).Type().Elem().Name()
m.Put(s, children)
for i := 0; i < tree.GetChildCount(); i++ {
nested := linkedhashmap.New()
children.Add(nested)
traverseMap(tree.GetChild(i), nested)
}
}
}

func main() {
input, _ := antlr.NewFileStream("../input/sample-mvbag-rich.toml")
lexer := parser.NewVeloLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
p := parser.NewVeloParser(stream)
p.RemoveErrorListeners()
p.AddErrorListener(errorListiner)
p.BuildParseTrees = true
tree := p.Velo()
j := toMap(tree)
println(j.Size())
strB, _ := j.ToJSON()
print(string(strB))
//antlr.ParseTreeWalkerDefault.Walk(NewVeloListener(), tree)
}

Screenshot 2019-08-22 at 15.00.08.png

adib.ras...@gmail.com

unread,
Jul 27, 2020, 12:31:52 PM7/27/20
to golang-nuts
Hi Gervasius,

Do you have the final solution of your work?

Thanks,
Reply all
Reply to author
Forward
0 new messages