Go to JSON
In daily work, except for data structures that need to be converted from JSON to Go. The opposite is often the case: we need to send the data as a JSON string to the Web server. Today we will learn how to encode JSON from structured data.
The structure is converted to JSON format
For example, we have the following structure:
type Student struct {
Name string
Age int
Address Address
}
type Address struct {
Road string
Street string
City string
Province string
Country string
}
Zhang3 := Student{
Name: "Zhang",
Age: 18,
Address: Address{
Road: "renmin south road",
Street: "123 street",
City: "cs",
Province: "hn",
Country: "CN",}}Copy the code
To encode the student in JSON format, we can use the json.marshl () function in the JSON package:
Info_of_Zhang3, err := json.Marshal(Zhang3)
if err == nil {
fmt.Println(string(Info_of_Zhang3))
} else {
fmt.Println(err)
return
}
Copy the code
The Marshal() function returns an encoded JSON (byte slice) and an error message (if there is an error). Then we can print the JSON string.
The complete code is as follows:
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
Address Address
}
type Address struct {
Road string
Street string
City string
Province string
Country string
}
func main(a) {
Zhang3 := Student{
Name: "Zhang",
Age: 18,
Address: Address{
Road: "renmin south road",
Street: "123 street",
City: "cs",
Province: "hn",
Country: "CN",
},
}
Info_of_Zhang3, err := json.Marshal(Zhang3)
if err == nil {
fmt.Println(string(Info_of_Zhang3))
} else {
fmt.Println(err)
return}}Copy the code
Run the code and get the following JSON data:
$ go run main.go
{"Name":"Zhang"."Age": 18."Address": {"Road":"renmin south road"."Street":"123 street"."City":"cs"."Province":"hn"."Country":"CN"}}
Copy the code
When you look at the JSON output, you may have noticed the lack of indentation. If you want to indent the output and format it nicely, you can use the json.marshalindent () function.
For example, use the following statement:
Info_of_Zhang3, err := json.MarshalIndent(Zhang3, ""."")
Copy the code
Function parsing: The second argument specifies the string at the beginning of each line of output. At the beginning of the output, the third argument specifies the string to indent each line. Json.MarshalIndent(Zhang3, “”, “”)
{
"Name": "Zhang"."Age": 18."Address": {
"Road": "renmin south road"."Street": "123 street"."City": "cs"."Province": "hn"."Country": "CN"}}Copy the code
The interface is converted to JSON format
Sometimes you don’t want to fix the number of fields in a structure. Instead, you want to be able to add additional data as needed. You can do this using an empty interface, as follows:
type Student map[string] interface{}
type Address map[string] interface{}
Copy the code
Using the empty interface, you can create your own Student variables and add the desired elements, like this:
Zhang3 := Student{
"Name": "Zhang"."Age": 18."Address": Address{
"Road": "renmin south road"."Street": "123 street"."City": "cs"."Province": "hn"."Country": "CN",},"Year": 2022.// Add a new school year
}
Copy the code
The complete code is as follows:
package main
import (
"encoding/json"
"fmt"
)
type Student map[string]interface{}
type Address map[string]interface{}
func main(a) {
Zhang3 := Student{
"Name": "Zhang"."Age": 18."Address": Address{
"Road": "renmin south road"."Street": "123 street"."City": "cs"."Province": "hn"."Country": "CN",},"Year": 2022.// Add a new school year
"GraduateAt": 2026.// Year of graduation
}
InfoOfZhang3, err := json.MarshalIndent(Zhang3, ""."")
if err == nil {
fmt.Println(string(InfoOfZhang3))
} else {
fmt.Println(err)
}
}
Copy the code
The code output is:
{
"Address": {
"City": "cs"."Country": "CN"."Province": "hn"."Road": "renmin south road"."Street": "123 street"
},
"Age": 18."GraduateAt": 2026."Name": "Zhang"."Year": 2022
}
Copy the code
We can also see that the order of the keys in the output JSON is alphabetical.
Prototype of the Marshal() function
Let’s look at the Marshal function:
func Marshal(v interface{}) ([]byte, error) {
e := newEncodeState()
err := e.marshal(v, encOpts{escapeHTML: true})
iferr ! =nil {
return nil, err
}
buf := append([]byte(nil), e.Bytes()...)
e.Reset()
encodeStatePool.Put(e)
return buf, nil
}
Copy the code
- The function can take interface data of any type, v, and convert it to a byte array type. The return value is JSON data and error messages. If the conversion succeeds, then
err == nil
; - In the process of converting objects to JSON, the following principles are followed: a. Boolean is still Boolean after being converted to JSON. B. Regular numbers in the FLOATING point type after conversion to JSON; C. Strings are converted to Unicode strings in UTF-8 encoding, and special characters are escaped. D. Arrays and slices are converted to arrays in JSON, []byte classes are converted to Base64 encoded strings, and slice zero values are converted to NULL; E. Convert struct to JSON object, and only the variables in the struct must be capitalized before the exported fields can be converted to output, and these fields will be used as string indexes of the JSON object; F. When converting a map data structure, the data type must be
map[string]T
,T
Can beencoding/json
Any type supported by the package.
conclusion
In the previous article, you saw how to decode JSON data into the Unmarshal function of the Go language’s corresponding structure.
In this paper, the common structures and interfaces of Go language are simply converted into JSON data, and other types are similar. Finally, the prototype of the coded function Marshal() is given and simply explained.
In addition, the Encoding/JSON package provides Encode() and Decode() functions for formatting a single object, while the Marshal() and Unmarshal() functions work on multiple objects and byte streams.
In fact, this article is only a brief introduction to Go and JSON data conversion on the console. Later articles will cover file reading and writing, so you can learn to work with JSON files. Stay tuned!
Here is one of the millet in the universe, a foreign company worker with more hair than ideas! If you like my article, follow me, click “like”, let me know you exist, thank you! 2022, come on