go语言中json数据的读取和写出操作


Posted in Golang onApril 28, 2021

go自带json库,在使用时需要通过 import "encoding/json"来导入该库。

在读取和写入json数据之前需要定义相关的结构体来对应被操作的json数据的格式,并且结构体中需要导出或导入的变量首字母大写。

其中,json.Marshal()用于将一个对象转换为json格式的字节数组,json.Unmarshal()用于将json格式的字节数组转换为一个对象。

具体使用示例如下所示:

首先,定义结构体:

type Com struct {                                                                                                                                                          
        Name string
        Nodes []string
}

读取操作(从文件中读取json数组到结构体数组中):

func load(fname string) {
        var cs []Com = make([]Com, 0)
        fp, err := os.Open(fname)
        if err != nil {
                panic(err)
        }      
        defer fp.Close()
        bytes, err := ioutil.ReadAll(fp)
        if err != nil {
                panic(err)
        }      
        err = json.Unmarshal(bytes, &cs)
        if err != nil {
                panic(err)
        }
        //使用cs
        ...       
}

写出操作(将结构体数组转换为json数组并写入文件):

func dump(fname string) {
        fp, err := os.Create(fname)
        if err != nil {
                panic(err)
        }  
        defer fp.Close()
        cs := []Com{}
        cs = append(cs, Com{"1", []string{"1.1", "2.2"}})
        cs = append(cs, Com{"2", []string{"2.2", "3.2"}})
        cs = append(cs, Com{"3", []string{"3.4", "4.5"}})
        data, err := json.Marshal(cs)
        if err != nil {
                panic(err)
        }  
        n, err := fp.Write(data)
        if err != nil {
                panic(err)
        }  
}

补充:go 读取 json 配置文件

引言

go 读取 json 配置文件,主要有两个知识点:一是文件的读取,二是 json 数据的处理。

序列化与反序列化

对 json 数据的处理往往指的是数据的序列化和反序列化。

把变量从内存中变成可存储或传输的过程称之为序列化,序列化之后,就可以把序列化后的内容写入到磁盘,或者通过网络传输到别的机器上。反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化。

go 有内置对 json 数据的处理包 “encoding/json”。

序列化为 json 格式:

data, err := json.Marshal(infos)

反序列化 json 数据:

err := json.Unmarshal(str, &info)

文件读取

配置文件的读取

config.json

{
  "userName":"root",
  "password":"",
  "host":"localhost",
  "port":"3306",
  "dbName": "test",
  "tableName":"table"
}

config.go

package main
import (
 "encoding/json"
 "fmt"
 "sync"
 io "io/ioutil"
)
//定义配置文件解析后的结构
type UserInfo struct {
 UserName  string `json:userName`
 Password  string `json:password`
 Host      string `json:host`
 Port     string `json:port`
 DbName    string `json:dbName`
 TableName string `json:tableName`
}
var UserIn UserInfo
var file_locker sync.Mutex //config file locker
func InitConfig() bool {
 conf, bl := LoadConfig("./config.json") //get config struct
 if !bl {
  fmt.Println("InitConfig failed")
  return false
 }
 UserIn = conf
 return true
}
/*************************************************
Function: LoadConfig
Description: read config file to config struct
@parameter filename: config file
Return: Config,bool
*************************************************/
func LoadConfig(filename string) (UserInfo, bool) {
 var conf UserInfo
 file_locker.Lock()
 data, err := io.ReadFile(filename) //read config file
 file_locker.Unlock()
 if err != nil {
  fmt.Println("read json file error")
  return conf, false
 }
 datajson := []byte(data)
 err = json.Unmarshal(datajson, &conf)
 if err != nil {
  fmt.Println("unmarshal json file error")
  return conf, false
 }
 return conf, true
}
func main() {
 bl := InitConfig()
 if !bl {
  fmt.Println("init config failed")
  return
 }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。如有错误或未考虑完全的地方,望不吝赐教。

Golang 相关文章推荐
Go缓冲channel和非缓冲channel的区别说明
Apr 25 Golang
Go语言带缓冲的通道实现
Apr 26 Golang
golang http使用踩过的坑与填坑指南
Apr 27 Golang
Golang 如何实现函数的任意类型传参
Apr 29 Golang
解决Go gorm踩过的坑
Apr 30 Golang
go 实现简易端口扫描的示例
May 22 Golang
再次探讨go实现无限 buffer 的 channel方法
Jun 13 Golang
Go语言基础知识点介绍
Jul 04 Golang
Golang表示枚举类型的详细讲解
Sep 04 Golang
golang生成并解析JSON
Apr 14 Golang
GO语言异常处理分析 err接口及defer延迟
Apr 14 Golang
golang 实现菜单树的生成方式
Apr 28 #Golang
golang通过递归遍历生成树状结构的操作
Apr 28 #Golang
goland 恢复已更改文件的操作
goland 清除所有的默认设置操作
go 原生http web 服务跨域restful api的写法介绍
Apr 27 #Golang
解决Golang中ResponseWriter的一个坑
Apr 27 #Golang
golang在GRPC中设置client的超时时间
You might like
php求正负数数组中连续元素最大值示例
2014/04/11 PHP
PHP实现删除多重数组对象属性并重新赋值的方法
2017/06/07 PHP
JavaScript中Array 对象相关的几个方法
2006/12/22 Javascript
用js实现的抽象CSS圆角效果!!
2007/05/03 Javascript
javascript工具库代码
2012/03/29 Javascript
js切换div css注意的细节
2012/12/10 Javascript
Node.js和PHP根据ip获取地理位置的方法
2014/03/14 Javascript
解决JavaScript数字精度丢失问题的方法
2015/12/03 Javascript
用js读写cookie的简单方法(推荐)
2016/08/08 Javascript
Node.js的环境安装配置(使用nvm方式)
2016/10/11 Javascript
ES6新特性之解构、参数、模块和记号用法示例
2017/04/01 Javascript
vue2.0的contextmenu右键弹出菜单的实例代码
2017/07/24 Javascript
详解express使用vue-router的history踩坑
2019/06/05 Javascript
使用setup.py安装python包和卸载python包的方法
2013/11/27 Python
Python程序设计入门(3)数组的使用
2014/06/16 Python
python入门前的第一课 python怎样入门
2018/03/06 Python
OPENCV去除小连通区域,去除孔洞的实例讲解
2018/06/21 Python
python删除列表元素的三种方法(remove,pop,del)
2019/07/22 Python
Djang的model创建的字段和参数详解
2019/07/27 Python
python单线程下实现多个socket并发过程详解
2019/07/27 Python
python定义类self用法实例解析
2020/01/22 Python
python 获取当前目录下的文件目录和文件名实例代码详解
2020/03/10 Python
python代码实现将列表中重复元素之间的内容全部滤除
2020/05/22 Python
基于Python词云分析政府工作报告关键词
2020/06/02 Python
解析Python 偏函数用法全方位实现
2020/06/26 Python
python 删除系统中的文件(按时间,大小,扩展名)
2020/11/19 Python
Python3 用什么IDE开发工具比较好
2020/11/28 Python
如何写出高性能的JSP和Servlet
2013/01/22 面试题
2014年高三毕业生自我评价
2014/01/11 职场文书
《月光启蒙》教学反思
2014/03/01 职场文书
2014年作风建设心得体会
2014/10/22 职场文书
八年级上册语文教学计划
2015/01/22 职场文书
《静夜思》教学反思
2016/02/17 职场文书
MongoDB 常用的crud操作语句
2021/06/20 MongoDB
MySQL数据库完全卸载的方法
2022/03/03 MySQL
Golang Web 框架Iris安装部署
2022/08/14 Python