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 resContent
	err = 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格式数据流中字段,不报错

相关推荐
猷咪10 分钟前
C++基础
开发语言·c++
IT·小灰灰12 分钟前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧13 分钟前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q14 分钟前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳014 分钟前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾14 分钟前
php 对接deepseek
android·开发语言·php
2601_9498683618 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter
星火开发设计32 分钟前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
qq_1777673744 分钟前
React Native鸿蒙跨平台数据使用监控应用技术,通过setInterval每5秒更新一次数据使用情况和套餐使用情况,模拟了真实应用中的数据监控场景
开发语言·前端·javascript·react native·react.js·ecmascript·harmonyos
一匹电信狗1 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl