Go - How to create a parser

后端 未结 6 901
醉话见心
醉话见心 2020-12-22 23:16

I want to build a parser but have some problems understanding how to do this.

Sample string I would like to parse

{key1 = value1 | key2 = {key3 = val         


        
6条回答
  •  醉梦人生
    2020-12-22 23:59

    That particular format is very similar to json. You could use the following code to leverage that similarity:

        var txt = `{key1 = "\"value1\"\n" | key2 = { key3 = 10 } | key4 = {key5 = { key6 = value6}}}`
        var s scanner.Scanner
        s.Init(strings.NewReader(txt))
        var b []byte
    
    loop:
        for {
            switch tok := s.Scan(); tok {
            case scanner.EOF:
                break loop
            case '|':
                b = append(b, ',')
            case '=':
                b = append(b, ':')
            case scanner.Ident:
                b = append(b, strconv.Quote(s.TokenText())...)
            default:
                b = append(b, s.TokenText()...)
            }
        }
    
        var m map[string]interface{}
        err := json.Unmarshal(b, &m)
        if err != nil {
            // handle error
        }
    
        fmt.Printf("%#v\n",m)
    

提交回复
热议问题