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