The encoding/json library in the Go language provides complex functions to convert various types in Go and JSON formats. We mainly use the following functions:
- Serializes a slice, structure, or dictionary into a string [byte stream] in JSON format.
- Deserializes a JSON-formatted string [byte stream] into a slice, structure, or dictionary.
Serialization
Serialization uses the json libraryMarshal
function:
func Marshal(v interface{}) ([]byte, error)
1. Structure serialization
For example, use the following structure to represent a movie:
type Movie struct { Title string Year int `json:"released"` Color bool `json:"color,omitempty"` Actors []string }
The string followed by the type in the definitionjson:"released"
andjson:"color,omitempty
, calledfield tags, it tells the json library some rules when performing serialization:
-
json:"released"
Make the corresponding name after serialization "released", not "Year". -
json:"color,omitempty"
If the value of the Color member isfalse
, then ignore it and do not serialize it.
Some rules for serialization without field tags:
- If the name of a struct member does not begin with a capital letter, it is not serialized.
- If the name of a structure member starts with a capital letter, the serialized name is the member name.
The code for serialization is as follows:
movie := Movie{ Title: "Casablanca", Year: 1942, Color: false, Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}, } data, err := (movie) if err != nil { ("JSON marshaling failed: %s", err) } ("%s\n", data)
Output:
{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","Ingrid Bergman"]}
2. Dictionary serialization
To serialize a dictionary into - JSON format, its key must be a string.
Here is an example:
info := map[string]int{ "width": 1280, "height": 720, } data, err := (info, "", " ") if err != nil { ("JSON marshaling failed: %s", err) } ("%s\n", data)
Output:
{
"height": 720,
"width": 1280
}
Here we useMarshalIndent
Functions make the output JSON format easier to read. The serialized name is the name of the key in the dictionary.
3. Slice serialization
Let's take a look at an example:
type Movie struct { Title string Year int `json:"released"` Color bool `json:"color,omitempty"` Actors []string } var movies = []Movie{ { Title: "Casablanca", Year: 1942, Color: false, Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}, }, { Title: "Cool Hand Luke", Year: 1967, Color: true, Actors: []string{"Paul Newman"}, }, { Title: "Bullitt", Year: 1968, Color: true, Actors: []string{"Steve McQueen", "Jacqueline Bisset"}, }, } data, err := (movies, "", " ") if err != nil { ("JSON marshaling failed: %s", err) } ("%s\n", data)
Output:
[
{
"Title": "Casablanca",
"released": 1942,
"Actors": [
"Humphrey Bogart",
"Ingrid Bergman"
]
},
{
"Title": "Cool Hand Luke",
"released": 1967,
"color": true,
"Actors": [
"Paul Newman"
]
},
{
"Title": "Bullitt",
"released": 1968,
"color": true,
"Actors": [
"Steve McQueen",
"Jacqueline Bisset"
]
}
]
Deserialization
Deserialization useUnmarshal
function:
func Unmarshal(data []byte, v interface{}) error
1. Be sure to know the JSON format
We need to first represent the JSON format as a definite type.
1. The following JSON format:
{ "name": "Awesome 4K", "resolutions": [ { "width": 1280, "height": 720 }, { "width": 1920, "height": 1080 }, { "width": 3840, "height": 2160 } ] }
We can use the following structure to represent it:
struct { Name string Resolutions []struct { Width int Height int } }
2. The following JSON format:
{ "height": 720, "width": 1280 }
Can also be usedmap[string]int
, that is, a dictionary is used to represent it.
3. The following JSON format:
[ { "width": 1280, "height": 720 }, { "width": 1920, "height": 1080 }, { "width": 3840, "height": 2160 } ]
Using slices[]map[string]int
Let's express it.
Regardless, a definite JSON format can always be represented using slices, structures, or dictionaries.
Then deserialization can be performed:
var jsonBlob = []byte(` [ { "width": 1280, "height": 720 }, { "width": 1920, "height": 1080, }, { "width": 3840, "height": 2160 } ] `) di := []map[string]int{} err = (jsonBlob, &di) if err != nil { ("error:", err) } ("%+v\n", di)
Output
[map[height:720 width:1280] map[height:1080 width:1920] map[height:2160 width:3840]]
2. Unable to determine the JSON format
The format that cannot be determined can be used directlyinterface{}
Type to represent. At this time, if it is a JSON object, the json library will use it when deserializingmap[string]interface{}
Type to represent it. If it is a JSON array, it will use[]interface{}
Type to represent it. specificinterface{}
For the corresponding specific type, you need to use type assertions.
Let's take a look at an example:
package main import ( "encoding/json" "fmt" ) func main() { var jsonBlob = []byte(` { "name": "Awesome 4K", "price": 1999.9, "resolutions": [ { "width": 1280, "height": 720 }, { "width": 1920, "height": 1080 }, { "width": 3840, "height": 2160 } ] } `) var d interface{} err := (jsonBlob, &d) if err != nil { ("error:", err) } (d) m := d.(map[string]interface{}) for k, v := range m { switch vv := v.(type) { case string: (k, "is string", vv) case float64: (k, "is float64", vv) case []interface{}: (k, "is an array:") for i, u := range vv { (i, u) } default: (k, "is of a type I don't know how to handle") } } }
Output:
map[name:Awesome 4K price:1999.9 resolutions:[map[height:720 width:1280] map[height:1080 width:1920] map[height:2160 width:3840]]]
resolutions is an array:
0 map[height:720 width:1280]
1 map[height:1080 width:1920]
2 map[height:2160 width:3840]
name is string Awesome 4K
price is float64 1999.9
This is the end of this article about the use of the Go language JSON standard library. For more information about the Go language JSON standard library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!