When you want to save configuration in your project, what data format will you choose, you might sayyaml
Orjson
, 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 bejson
It's right.
About how to operate in GoJSON
, let’s explore this article!
JSON
What isJSON
?JSON
The 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 quotesUnicode
Character sequence. - Boolean(
bool)
:true
orfalse
。 - 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's
boolean
The 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's
chan
Complex types such as functions cannot be used as JSON values
Basic operations of JSON
Go language is inencoding/json
The package provides the operation of JSON data serialization and deserialization, the simplest and most direct way is to call it.Marshal
Serialize a Go data into a JSON data and callUnmarshal
Deserialize JSON data.
Marshal
json
PackedMarshal()
Functions are used to encode data into oneJSON
Text, the signature of the function is as follows:
func Marshal(v interface{}) ([]byte, error)
Marshal()
The function can accept any value and returnJSON
a byte array with aerror
type:
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 aboveMarshal
The 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.MarshalIndent
The function, the function signature is as follows:
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
Compared withMarshal
function,MarshalIndent
The function can receive aprefix
andindent
, 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 upindent
Running results after parameters:
{ "Go Ation": 2, "Go from Beginner to Mastery": 3, "Go Beginner": 1, "Go Advanced Programming": 4 }
json
PackedUnmarshal()
Function andMarshal
Just the contrary, used to convert oneJSON
The 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 tag
To define the field name of json.
Custom serialization
If it is a custom data type, we can implement itMarshaler
Interface andUnmarshaler
Interface method, the definition of these two interfaces is as follows:
type Unmarshaler interface { UnmarshalJSON([]byte) error } type Marshaler interface { MarshalJSON() ([]byte, error) }
When calledMarshal
When 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,Reason
It has also been achievedUnmarshaler
interface, so invokedUnmarshal
Called 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
CallMarshal
Only one byte array will be returned.Unmarshal
Functions 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 useEncoder
andDecoder
It will be more convenient.
NewEncoder
Functions can create aEncoder
Structure,NewEncoder
The function receives an implementationThe parameters of the interface will be called after serialization
Write 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.
NewDecoder
Functions can create aDecoder
Structure,NewDecoder
The function receives an implementationThe parameters of the interface, that is,
Decoder
fromRead 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
JSON
It is a very common data format and is often used in the front and back ends.api
Interface data communication, while Go language is in the standard libraryencoding/json
In the packageJSON
Data 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!