Read and write operations of JSON data in go language

Time:2021-11-25

Go comes with its own JSON library. When using, you need to import the library through import “encoding / JSON”.

Before reading and writing JSON data, you need to define the relevant structure to correspond to the format of the operated JSON data, and the variables to be exported or imported in the structure are capitalized.

Among them, JSON. Marshal () is used to convert an object into a byte array in JSON format, and JSON. Unmarshal () is used to convert a byte array in JSON format into an object.

Specific use examples are as follows:

First, define the structure:


type Com struct {                                                                                                                                                          
        Name string
        Nodes []string
}     

Read operation (read JSON array from file to structure array):

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)
        }
        //Use CS
        ...       
}

Write out operation (convert structure array to JSON array and write to file):


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)
        }  
}     

Supplement: go read JSON configuration file

introduction

Go reading JSON configuration files mainly has two knowledge points: one is file reading, and the other is JSON data processing.

Serializable and Deserialize

The processing of JSON data often refers to data serialization and deserialization.

The process of changing variables from memory to storable or transmissible is called serialization. After serialization, the serialized contents can be written to disk or transmitted to other machines through the network. Conversely, reading the contents of variables from serialized objects back into memory is called deserialization.

Go has a built-in processing package “encoding / JSON” for JSON data.

Serialize to JSON format:


data, err := json.Marshal(infos)

Deserialize JSON data:


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

File reading

Reading of configuration file

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"
)
//Define the structure of the configuration file after parsing
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
 }
}

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.