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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM