欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > go 读取json文件内容,并且解析内容到interface、 map、 struct

go 读取json文件内容,并且解析内容到interface、 map、 struct

2024/10/24 1:51:05 来源:https://blog.csdn.net/yuxuan89814/article/details/139522173  浏览:    关键词:go 读取json文件内容,并且解析内容到interface、 map、 struct

 1,解析到interface、 map

func ReadAllFileContent(fileName string) {file, err := os.Open(fileName)if err != nil {log.Fatal(err)}defer file.Close()// buf := make([]byte, 2024)data, err := ioutil.ReadAll(file) //读取的结果是[]byte类型if err != nil {log.Fatal(err)}var result interface{}err = json.Unmarshal(data, &result)if err != nil {log.Fatal(err)}fmt.Println(result)map_data := result.(map[string]interface{}) //interface如何转换为map:类型断言是类型安全的,并且只有当接口变量确实存储了你所期望的具体类型时才会成功。for k, v := range map_data {fmt.Println(k, v)}var result2 map[string]interface{}err = json.Unmarshal(data, &result2)if err != nil {log.Fatal(err)}fmt.Println("-------------")//一般写为如下形式if map_data2, ok := result2["data"].(map[string]interface{}); ok {fmt.Println(map_data2["name"])}}

打印结果:

msg ok
code 200
data map[age:18 name:张三 sex:男]
-------------
张三

注意:

1,读取文件使用ioutil.ReadAll,读取的结果是[]byte类型

    data, err := ioutil.ReadAll(file) 

2,   json.Unmarshal将[]byte类型转换为interface,  result是interface,使用的使用要类型转换   

    err = json.Unmarshal(data, &result) 

    map_data := result.(map[string]interface{})

   interface如何转换为map:类型断言是类型安全的,并且只有当接口变量确实存储了你所期望的具体类型时才会成功。

2,解析到struct

	type UserInfo struct {Name string `json:"name"`Age  int    `json:"age"`Sex  string `json:"sex"`}type resContent struct {Code int      `json:"code"`Msg  string   `json:"msg"`Data UserInfo `json:"data"`}fmt.Println("-------------")var result3 resContenterr = json.Unmarshal(data, &result3)if err != nil {log.Fatal(err)}fmt.Println(result3.Data.Name)fmt.Println(result3.Code)

struct内部属性大写, 否则无法引用。

`json:"code"`后是json格式数据流中对应的名称,写对了可以直接对应。

struct中多字段,缺少对应json格式数据流中字段,不报错

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com