SoFunction
Updated on 2025-03-05

Detailed explanation of JSON operation of re-learning Go language

When you want to save configuration in your project, what data format will you choose, you might sayyamlOrjson, When you want to return data to the front end as a backend, what data format will you choose? This time I think it must bejsonIt's right.

About how to operate in GoJSON, let’s explore this article!

JSON

What isJSONJSONThe full name isJavascript Object Notation, is a standard protocol for data structured interaction, which is very easy to read and write. It can save the application's relevant configuration information as a configuration file, or it can be used as a format for front-end interface data, such as the backend returns JSON data such as the front-end:

{
	"code":404,
	"msg":"Not Found"
}

JSON data type

JSON only supports six data types, namely:

  • number(number): There are two ways to express decimal and scientific mathematics.
  • String(string): represented in double quotesUnicodeCharacter sequence.
  • Boolean(bool)trueorfalse
  • Object(object): Use curly braces ({}) One or more key-value pairs enclosed (key/value),usecomma(,)Separate, the last key value pair cannot have a comma after it, the key (key) Must be double quotes ("") strings generated by , and the value can be of any type (such as: boolean, number, object, array, string).
  • Array(array): Use brackets ([]) The set of values ​​enclosed by any type (boolean, number, object, array, string).
  • null:null value.

Correlation between JSON type and Go data type:

  • Go'sbooleanThe bool type corresponding to JSON
  • Go's integer and floating point type correspond to JSON's number class
  • Go map and struct correspond to JSON object, map key must be a string
  • Go's slice and array correspond to JSON array
  • Go'schanComplex types such as functions cannot be used as JSON values

Basic operations of JSON

Go language is inencoding/jsonThe package provides the operation of JSON data serialization and deserialization, the simplest and most direct way is to call it.MarshalSerialize a Go data into a JSON data and callUnmarshalDeserialize JSON data.

Marshal

jsonPackedMarshal()Functions are used to encode data into oneJSONText, the signature of the function is as follows:

func Marshal(v interface{}) ([]byte, error) 

Marshal()The function can accept any value and returnJSONa byte array with aerrortype:

package main
import (
	"encoding/json"
	"fmt"
)
func main() {
	m := map[string]int{"Go Beginner": 1, "Go Ation": 2, "Go from Beginner to Mastery": 3, "Go Advanced Programming": 4}
	data, err := (m)
	if err != nil {
		panic(err)
	}
    //Convert to string and output	(string(data)) 
}

The running results of the above example program:

{"Go Ation":2,"Go from Beginner to Mastery":3,"Go Beginner":1,"Go Advanced Programming":4}

MarshalIndent

Called aboveMarshalThe data serialized by the function outputs a line. If the data is too long, it will be detrimental to our reading. If the output JSON data format is more friendly, you can use it.MarshalIndentThe function, the function signature is as follows:

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

Compared withMarshalfunction,MarshalIndentThe function can receive aprefixandindent, used to set the prefix and indentation of each line of output JSON. Here is an example of using this function:

package main
import (
	"encoding/json"
	"fmt"
)
func main() {
	m := map[string]int{"Go Beginner": 1, "Go Ation": 2, "Go from Beginner to Mastery": 3, "Go Advanced Programming": 4}
    //Set prefix to empty, indent to tab	data, err := (m, "", "\t")
	if err != nil {
		panic(err)
	}
	(string(data))
}

Set upindentRunning results after parameters:

{
	"Go Ation": 2,
    "Go from Beginner to Mastery": 3,
    "Go Beginner": 1,
    "Go Advanced Programming": 4
}

jsonPackedUnmarshal()Function andMarshalJust the contrary, used to convert oneJSONThe data format is deserialized into a Go type variable we defined, and the signature of the function is as follows:

func Unmarshal(data []byte, v interface{}) error 

Here is an example of deserialization:

package main
import (
	"encoding/json"
	"fmt"
)
type Book struct {
	BookName string `json:"name"`
	Number   int    `json:"num"`
}
func main() {
	jsonStr := `[{"name":"Go Beginner","num": 1}, {"name":"Go Ation","num": 2}, {"name":"Go from Beginner to Mastery","num": 3}, {"name":"Go Advanced Programming","num": 4}]`
	var books []Book
	err := ([]byte(jsonStr), &books)
	if err != nil {
		panic(err)
	}
	(books)
}

In the above example, we desorted a JSON into an array, and the elements of the array are a custom struct type, which can be passed in struct.json tagTo define the field name of json.

Custom serialization

If it is a custom data type, we can implement itMarshalerInterface andUnmarshalerInterface method, the definition of these two interfaces is as follows:

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}
type Marshaler interface {
	MarshalJSON() ([]byte, error)
}

When calledMarshalWhen the function is serialized, it will be calledMarshalJSON()Functions, we can customize the serialization logic in this function:

package main
import (
	"encoding/json"
	"fmt"
	"strings"
)
type Reason uint8
const (
	Unknown = iota
	Spring
	Summer
	Autumn
	Winter
)
//Customized antisequence logicfunc (r *Reason) UnmarshalJSON(b []byte) error {
	var s string
	if err := (b, &s); err != nil {
		return err
	}
	switch (s) {
	default:
		*r = Unknown
	case "spring":
		*r = Spring
	case "summer":
		*r = Summer
	case "autumn":
		*r = Autumn
	case "winter":
		*r = Winter
	}
	return nil
}
//Customize sequence logicfunc (r Reason) MarshalJSON() ([]byte, error) {
	var s string
	switch r {
	default:
		s = "unknonw"
	case Spring:
		s = "spring"
	case Summer:
		s = "summer"
	case Autumn:
		s = "autumn"
	case Winter:
		s = "winter"
	}
	return (s)
}
func main() {
	r := []Reason{1, 2, 3, 4}
	data, err := (r)
	if err != nil {
		panic(err)
	}
	(string(data))
}

In the above code,ReasonIt has also been achievedUnmarshalerinterface, so invokedUnmarshalCalled when deserializing the functionUnmarshalJSON, In this method we can customize the logic of deserialization:

func main() {
	jsonStr := `["winter","spring","test"]`
	var r []Reason
	err := ([]byte(jsonStr), &r)
	if err != nil {
		panic(err)
	}
	(r)
} 

Encoder and Decoder

CallMarshalOnly one byte array will be returned.UnmarshalFunctions can only pass in one byte array. If we want to write serialized data to different places (such as saving to a file), or want to read JSON data from different places (such as reading from a file), then useEncoderandDecoderIt will be more convenient.

NewEncoderFunctions can create aEncoderStructure,NewEncoderThe function receives an implementationThe parameters of the interface will be called after serializationWrite data:

package main
import (
	"encoding/json"
	"os"
)
func main() {
	m := map[string]int{"Go Beginner": 1, "Go Ation": 2, "Go from Beginner to Mastery": 3, "Go Advanced Programming": 4}
	file, err := ("")
	if err != nil {
		panic(err)
	}
    defer ()
	encoder := (file)
	("", "\t")
	err = (m)
	if err != nil {
		panic(err)
	}
}

After the above program is run, the JSON data will be saved to the current directory.in the file.

NewDecoderFunctions can create aDecoderStructure,NewDecoderThe function receives an implementationThe parameters of the interface, that is,DecoderfromRead data in:

package main
import (
	"encoding/json"
	"fmt"
	"os"
)
func main() {
	file, err := ("")
	if err != nil {
		panic(err)
	}
	defer ()
	decoder := (file)
	var m map[string]int
	err = (&m)
	if err != nil {
		panic(err)
	}
	(m)
}

summary

JSONIt is a very common data format and is often used in the front and back ends.apiInterface data communication, while Go language is in the standard libraryencoding/jsonIn the packageJSONData encoding and decoding provide very good support.

OK, I believe that after reading this article, you should have mastered the following points:

  • What is JSON
  • How to serialize and deserialize JSON data
  • How to customize the serialization process
  • Use with

This is the end of this article about the detailed explanation of JSON operation of re-learning Go language. For more related Go JSON content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!