How to deal with JSON in Go language
This article mainly introduces "how to deal with JSON in Go language". In daily operation, I believe many people have doubts about how to deal with JSON in Go language. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to deal with JSON in Go language". Next, please follow the editor to study!
1. Encode to JSON format
Use the json.Marshal () function to encode a set of data in JSON format. The declaration of the json.Marshal () function is as follows:
If you have the following structure of type Book:
And there is an instance object of type Book as follows:
We can then use the json.Marshal () function to generate a piece of text in JSON format from the gobook instance:
If the encoding is successful, err will be assigned to a zero value nil, and the variable b will be a [] byte type formatted by JSON:
When we call the json.Marshal (gobook) statement, we iterate through the gobool object recursively. If we find that the data structure gobook implements the json.Marshaler interface and contains valid values, Marshal () will call its MarshalJSON () method to generate the data structure into text in JSON format.
Most data types of the Go language can be converted to valid JSON text, with the exception of channel, complex, and functions.
If a pointer appears in the pre-conversion data structure, the value referred to by the pointer will be converted, and if the pointer points to a zero value, then nill will be output as a result of the conversion.
In Go, the data type mappings before and after JSON conversion are as follows:
Boolean values are still of Boolean type when converted to JSON.
Floating-point numbers and integers are converted to regular numbers in JSON.
The string will be converted in UTF-8 to a string in the Unicode character set, such as special characters such as