golang json読み書きプロファイル
3302 ワード
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
転載先:https://www.cnblogs.com/pu369/p/10535478.html