Go - How to create a parser

后端 未结 6 920
醉话见心
醉话见心 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条回答
  •  Happy的楠姐
    2020-12-22 23:36

    If you are willing to convert your input to a standard JSON format, why create a parser when there are Go libraries that do the heavy lifting for you?

    Given the following input file (/Users/lex/dev/go/data/jsoncfgo/fritjof.json):

    Input File

    {
       "key1": "value1",
       "key2" :  {
          "key3": "value3"
       },
       "key4": {
          "key5": {
             "key6": "value6"
          }
       }
    }
    

    Code Example

    package main
    
    import (
        "fmt"
        "log"
        "github.com/l3x/jsoncfgo"
    )
    
    
    func main() {
    
        configPath := "/Users/lex/dev/go/data/jsoncfgo/fritjof.json"
        cfg, err := jsoncfgo.ReadFile(configPath)
        if err != nil {
            log.Fatal(err.Error())  // Handle error here
        }
    
        key1 := cfg.RequiredString("key1")
        fmt.Printf("key1: %v\n\n", key1)
    
        key2 := cfg.OptionalObject("key2")
        fmt.Printf("key2: %v\n\n", key2)
    
        key4 := cfg.OptionalObject("key4")
        fmt.Printf("key4: %v\n\n", key4)
    
        if err := cfg.Validate(); err != nil {
            defer log.Fatalf("ERROR - Invalid config file...\n%v", err)
            return
        }
    }
    

    Output

    key1: value1
    
    key2: map[key3:value3]
    
    key4: map[key5:map[key6:value6]]
    

    Notes

    jsoncfgo can handle any level of nested JSON objects.

    For details see:

    • http://l3x.github.io/golang-code-examples/2014/07/24/jsoncfgo-config-file-reader.html
    • http://l3x.github.io/golang-code-examples/2014/07/25/jsoncfgo-config-file-reader-advanced.html

提交回复
热议问题