Implementation of Go JSON encoding and decoding

  • 2020-07-21 08:21:41
  • OfStack

When developing applications, it is inevitable for clients (front-end pages or APP) to interact with servers. When transferring data in the interactive process, the most common and popular format is JSON. Go language provides encoding/json package for processing the encoding and decoding of JSON data.

In addition to JSON, XML is also commonly used for data interactions on the front and back ends, although JSON is more widely used due to its simplicity, readability, and popularity.

JSON profile

1. What is JSON?

JSON is fully called Javascript Object Notation, a standard protocol for structured data interaction, easy to read and write, so it is widely used in data interaction.

2. Data types in JSON

Numbers: there are two representations of decimal system and scientific notation mathematics. String: A sequence of Unicode characters represented by double quotes. Bull: true or false. Object: One or more key-value pairs (key/value) enclosed in curly braces ({}), separated by commas (,). The last key-value pair must not be followed by commas. Keys must be strings caused by double quotation marks (""), and values are of a literal type (Boolean, number, object, array, string). Array: A collection of bracketed ([]) values of any type (Boolean, number, object, array, string).

The following example is an array containing two objects.

[

[{"id":1,"username":"xiaoming","gender":1,"email":"xiaoming@163.com"},{"id":2,"username":"xiaohong","gender":2,"email":"xiaohong@163.com"}]

]

3. Combination of JSON and GO

When encoding/json is used to encode and decode JSON, the correspondence between JSON data type and Go language data type must be handled well.

The number, string, Boolean, and so on of JSON correspond to the corresponding built-in data type 11 in the Go language. An array of JSON corresponds to an array of Go or an Slice(slice). Objects of JSON correspond to struct(structure) or map of Go.

When encoding 1 struct, only uppercase members of the struct are encoded, lowercase members are ignored, and fields in the struct are allowed to declare the Tag of the member in backquotes to indicate the metafunction of the member.


type Member struct {
  Id    int  `json:"id"`
  Username string `json:"username"`
  Sex   uint  `json:"gender"`
  Email  string `json:"email"`
}

In the structure Member above, four members are defined and the Tag information of each member is declared, among which the Tag information of Sex is declared as gender, so the encoded result is:

[

[{"id":1,"username":"xiaoming","gender":1,"email":"xiaoming@163.com"},{"id":2,"username":"xiaohong","gender":2,"email":"xiaohong@163.com"}]

]

coding

The serialization of Go language data into JSON strings is called encoding. The result is one JSON string.

1. json. Marshal function

You can directly encode any data type using the json.Marshal function.


import (
  "encoding/json"
  "fmt"
)
func main() {
members := []Member{
  {
    Id:1,
    Username:" Xiao Ming ",
    Sex:1,
    Email:"xiaoming@163.com",
  },
  {
    Id:2,
    Username:" The little red ",
    Sex:1,
    Email:"xiaohong@163.com",
  },
  {
    Id:3,
    Username:" xiaohua ",
    Sex:2,
    Email:"xiaohua@163.com",
  },
}
  data,_ := json.Marshal(members)
  fmt.Printf("%s",data)
}

Operation results:

[

[{" id ": 1," username ":" xiao Ming ", "gender" : 1, "email" : "xiaoming@163.com"}, {" id ": 2," username ":" little red ", "gender" : 1, "email" : "xiaohong@163.com"}, {" id ": 3," username ":" xiao hua ", "gender" : 2, "email" : "ES 118 en@163.com}] ""

]

2. json.Encoder

json.Marshal is really just an encapsulation of ES129en.Encoder, so json.Encoder can also encode JSON.


func main(){
  b := &bytes.Buffer{}
  encoder := json.NewEncoder(b)
  err := encoder.Encode(members)
  if err != nil{
   panic(err)
  }
  fmt.Println(b.String())
}

decoding

Deserialize the JSON string into a work of the corresponding type of Go, called decoding.

1. json. Unmarshal function

json.Unmarshal is used to decode the JSON string as opposed to the ES151en.Marshal function.


func main() {
  str := `[
  {
    "id": 1,
    "username": " Xiao Ming ",
    "gender": 1,
    "email": "xiaoming@163.com"
  },
  {
    "id": 2,
    "username": " The little red ",
    "gender": 1,
    "email": "xiaohong@163.com"
  },
  {
    "id": 3,
    "username": " xiaohua ",
    "gender": 2,
    "email": "xiaohua@163.com"
  }
  ]`
  b := bytes.NewBufferString(str)
  var members []Member
  err := json.Unmarshal(b.Bytes(),&members)
  if err != nil{
    panic(err)
  }
  fmt.Println(members)
}

Operation results:

[

[{1 Xiaoming 1 xiaoming@163.com} {2 Xiahong 1 xiaohong@163.com} {3 Xiaohua 2 xiaohua@163.com}]

]

2. json.Decoder


func main(){
  b := bytes.NewBufferString(str)
  var members []Member
 decoder := json.NewDecoder(b)
 err = decoder.Decode(&members)
 if err != nil{
 panic(err)
 }
 fmt.Println(members)
}

summary

encoding/json in Go language provides various convenient methods for encoding and decoding JSON data. As long as we use it directly, we can complete various processing operations related to JSON, which is very simple and convenient.


Related articles: