golang json 读写配置文件
package main import ( "encoding/json" "fmt" "os" ) type configuration struct { Enabled bool Path string } /* config.json内容为: { "enabled": true, "path": "/usr/local" } { "enabled": false, "path": "/usr/local1" } */ func main() { //解码 //以只读方式打开config.json file, _ := os.Open("conf.json") defer file.Close() decoder := json.NewDecoder(file) conf := configuration{} for decoder.More() { err := decoder.Decode(&conf) if err != nil { fmt.Println("Error:", err) } fmt.Println(conf) } //编码 //以用户可读写方式打开config.json f, _ := os.OpenFile("conf.json", os.O_APPEND, 0644) defer f.Close() enc := json.NewEncoder(f) conf.Enabled = false conf.Path = "aa" enc.Encode(conf) }
补充:用缓存,可以将上面的
decoder := json.NewDecoder(file)
改为
r1 := bufio.NewReader(file)
decoder := json.NewDecoder(r1)
参考 https://blog.csdn.net/wade3015/article/details/83351776