Writing in the front

In our previous article, “Reading and writing Data in Golang (Middle),” we learned how to read command line arguments in Golang, and next we’ll learn about data formatting in Golang.

We all know that data must be encoded and decoded in order to be transferred over the network or saved in a file. Common encoding formats include JSON and XML.

Some additions to the concept

Encoding: The process from a particular data structure to a data stream

Decoding: Decoding is the reverse process of encoding, i.e. the process from data stream to data structure

Serialization: The process of capturing data in memory into a specified format, such as converting a Java object to a string

Next we’ll look at encoding data as JSON in Golang, using the Encoding library for this part

JSON data manipulation

To illustrate this section, I have copied the structures we used earlier when we studied them below

/ / cultivate immortality
type Immortal struct {
	Name   string
	Age    int
	Gender string
}
Copy the code

Then take a look at this example:

package main

import (
	"encoding/json"
	"fmt"
)

/ / cultivate immortality
type Immortal struct {
	Name   string
	Age    int
	Gender string
}

func main(a) {

	immortal := &Immortal{
		Name:   Mr.han "",
		Age:    18,
		Gender: "Men",}// Encode immortal Hanli as JSON []byte
	jsonByteImmortal, _ := json.Marshal(immortal)

	fmt.Printf("%s\n", jsonByteImmortal)
}

Copy the code

Output:

{"Name":Mr.han ""."Age":18."Gender":"Men"}
Copy the code

The json.Marshal function is signed by func Marshal(v interface{}) ([]byte, error), which returns an array of bytes.

JSON corresponds to the Go type as follows:

  • Bool Indicates a Boolean corresponding to JSON
  • Float64 Specifies the number of the JSON
  • String corresponds to the STRING of JSON
  • Nil corresponds to JSON null

Not all data can be encoded as JSON: only validated data structures can be encoded:

  • JSON objects support only strings of keys. To encode a Go map type, map must be map[string]T (T isjsonAny type supported in the package)
  • Channels, complex types, and function types cannot be encoded
  • Circular data structures are not supported; This will cause serialization to go into an infinite loop
  • Pointers can be encoded, essentially encoding the value to which the pointer points (or pointer is nil)

Deserialization operation

How do YOU convert a JSON in Golang to a data structure in Golang?

Look at the following example:

package main

import (
	"encoding/json"
	"fmt"
)

/ / cultivate immortality
type Immortal struct {
	Name   string
	Age    int
	Gender string
}


func main(a) {

	immortal := &Immortal{
		Name:   Mr.han "",
		Age:    18,
		Gender: "Men",
	}

	jsonImmortal, _ := json.Marshal(immortal)


	fmt.Printf("%s\n", jsonImmortal)

	// 1. Know the corresponding data type of JSON in advance
	 var jsonValue Immortal

	json.Unmarshal(jsonImmortal, &jsonValue)

	fmt.Println("name",jsonValue.Name)
	fmt.Println("age",jsonValue.Age)
	fmt.Println("gender",jsonValue.Gender)

	// 2. Do not know the corresponding data structure of JSON
	var m interface{}
	json.Unmarshal(jsonImmortal,&m)

	jsonMap := m.(map[string]interface{})
	for key, value := range jsonMap {
		printJson(key,value)
	}


}

func printJson(key string, value interface{}) {

		switch value.(type) {
		case string:
			fmt.Println(key,"value is a string: ",value)
		case float64:
			fmt.Println(key,"value is int type: ",value)
		case []interface{}:
			fmt.Println(key,"value is a array",value)
		case map[string]interface{}:
			m:= value.(map[string]interface{})
			for k, v := range m {
				printJson(k,v)
			}
			
		}


}
Copy the code

Output:

{"Name":" han Li ","Age":18,"Gender":" male "} Name Han Li Age 18 Gender male Name value is a string: Han Li Age value is int type: 18 Gender value is a string: maleCopy the code

In this example, there are two cases:

In the first case, if we know the structure of the JSON data in advance, we call the json.Unmarshal function to decode (or deserialize) it and store it in the memory address pointed to by the pointer variable of the data structure.

In the second case, we do not know the corresponding data structure of the JSON data in advance, so we can use type assertion techniques to get the corresponding key: value value of the JSON data.

Decodes and encodes JSON data streams

Json packages provide Decoder and Encoder types to support reading and writing of common JSON data streams. The NewDecoder and NewEncoder functions encapsulate IO.Reader and IO.Writer interfaces, respectively.

func NewDecoder(r io.Reader) *Decoderfunc NewEncoder(w io.Writer) *Encoder
Copy the code

To write JSON directly to a file, initialize the file with json.newencoder (or any type that implements io.writer) and call Encode(); The converse is to use json.newdecoder and Decode() functions:

func NewDecoder(r io.Reader) *Decoderfunc (dec *Decoder) Decode(v interface{}) error
Copy the code

Write in the last

That’s all we need to do to parse and transform JSON data in Golang. The examples covered in this article can be downloaded here. If my study notes can help you, please give me a thumbs up and encouragement. If there are mistakes and omissions in the article, please help to correct them.

In the next article, we’ll take a look at Gob, a unique encoding format in Golang