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
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: