Golang 讀取json文件,並解析結構體


代碼

https://github.com/smallinsect/MyGo/tree/master/myjson

MyUsers.json文件內容

{
    "name": "小昆蟲",
    "age": 2233,
    "account_id": "2222222aaaaa",
    "password": "******",
    "RMB": 66.66,
    "sex": false 
}

結構體

type User struct {
    Name       string  `json:"name"`
    Age        int64   `json:"age"`
    Account_id string  `json:"account_id"`
    Password   string  `json:"password"`
    RMB        float64 `json:"RMB"`
    Sex        bool    `json:"sex"`
}

執行代碼

    bytes, err := ioutil.ReadFile("./MyUsers.json")
    if err != nil {
        fmt.Println("讀取json文件失敗", err)
        return
    }
    u := &User{}
    err = json.Unmarshal(bytes, u)
    if err != nil {
        fmt.Println("解析數據失敗", err)
        return
    }
    fmt.Printf("%+v\n", u)

運行結果

 


免責聲明!

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



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