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
", u)

运行结果

原文地址:https://www.cnblogs.com/xuqiulin/p/13306537.html